Elffuss BraidHub

kikocis/continue public

4b606125a269 · 32.5 KiBRawPermalink
1import {
2 ActionReducerMapBuilder,
3 AsyncThunk,
4 PayloadAction,
5 createSelector,
6 createSlice,
7} from "@reduxjs/toolkit";
8import { JSONContent } from "@tiptap/react";
9import {
10 ApplyState,
11 AssistantChatMessage,
12 ChatHistoryItem,
13 ChatMessage,
14 ContextItem,
15 ContextItemWithId,
16 FileSymbolMap,
17 MessageModes,
18 PromptLog,
19 RuleWithSource,
20 Session,
21 SessionMetadata,
22 ThinkingChatMessage,
23 Tool,
24 ToolCallDelta,
25 ToolCallState,
26} from "core";
27import { BuiltInToolNames } from "core/tools/builtIn";
28import { NEW_SESSION_TITLE } from "core/util/constants";
29import {
30 renderChatMessage,
31 renderContextItems,
32} from "core/util/messageContent";
33import { findUriInDirs, getUriPathBasename } from "core/util/uri";
34import { findLastIndex } from "lodash";
35import { v4 as uuidv4 } from "uuid";
36import { type InlineErrorMessageType } from "../../components/mainInput/InlineErrorMessage";
37import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/utils";
38import { addToolCallDeltaToState } from "../../util/toolCallState";
39import { RootState } from "../store";
40import { streamResponseThunk } from "../thunks/streamResponse";
41import { findChatHistoryItemByToolCallId, findToolCallById } from "../util";
42
43/**
44 * Helper function to filter out duplicate edit/search-replace tool calls.
45 * Only keeps the first occurrence of edit tools.
46 *
47 * We don't support multiple parallel apply calls - see tool definitions for
48 * instructions we provide to models to prevent this behavior.
49 */
50function filterMultipleEditToolCalls(
51 toolCalls: ToolCallDelta[],
52): ToolCallDelta[] {
53 const editToolNames = [
54 BuiltInToolNames.EditExistingFile,
55 BuiltInToolNames.SearchAndReplaceInFile,
56 ];
57 let hasSeenEditTool = false;
58
59 return toolCalls.filter((toolCall) => {
60 const isEditTool = editToolNames.includes(toolCall.function?.name as any);
61
62 if (isEditTool) {
63 if (hasSeenEditTool) {
64 return false; // Skip this duplicate edit tool
65 }
66 hasSeenEditTool = true;
67 }
68
69 return true;
70 });
71}
72
73/**
74 * Initializes tool call states for a new message containing tool calls.
75 * This function is called when we receive a complete message with tool calls,
76 * typically in non-streaming scenarios or when processing the first chunk
77 * of a streaming message that contains tool calls.
78 *
79 * @param message - The chat message containing tool calls to process
80 * @param lastItem - The chat history item to attach tool call states to
81 */
82export function handleToolCallsInMessage(
83 message: ChatMessage,
84 lastItem: ChatHistoryItemWithMessageId,
85): void {
86 if (
87 (message.role === "assistant" || message.role === "thinking") &&
88 message.toolCalls?.length
89 ) {
90 // Filter out duplicate edit/search-replace tool calls - only keep the first one
91 const filteredToolCalls = filterMultipleEditToolCalls(message.toolCalls);
92
93 // Initialize tool call states for each filtered tool call in the message
94 // Each tool call gets its own state to track generation/execution progress
95 lastItem.toolCallStates = filteredToolCalls.map((toolCallDelta) =>
96 addToolCallDeltaToState(toolCallDelta, undefined),
97 );
98
99 // Update the message's toolCalls array to reflect the processed tool calls
100 // We can safely cast because we verified the role above
101 const curMessage = lastItem.message as
102 | AssistantChatMessage
103 | ThinkingChatMessage;
104 curMessage.toolCalls = lastItem.toolCallStates.map(
105 (state) => state.toolCall,
106 );
107 }
108}
109
110/**
111 * Applies a single tool call delta to the tool call states array.
112 *
113 * This function handles the core logic for OpenAI-style tool call streaming where:
114 * - Initial tool calls come with full details (ID, name, arguments)
115 * - Subsequent argument fragments come without IDs and need to update the most recent tool call
116 * - Multiple parallel tool calls can be streamed simultaneously
117 *
118 * @param toolCallDelta - The incoming tool call delta from the LLM stream
119 * @param toolCallStates - Array of existing tool call states (modified in place)
120 */
121function applyToolCallDelta(
122 toolCallDelta: ToolCallDelta,
123 toolCallStates: ToolCallState[],
124): void {
125 // Find existing state by matching toolCallId - this ensures we update
126 // the correct tool call even when multiple tool calls are being streamed
127 let existingStateIndex = -1;
128
129 if (toolCallDelta.id) {
130 // Tool call has an ID - find by exact match
131 // This handles: new tool calls or explicit updates to existing ones
132 existingStateIndex = toolCallStates.findIndex(
133 (state) => state.toolCallId === toolCallDelta.id,
134 );
135 } else {
136 // No ID in delta (common in OpenAI streaming fragments)
137 // Strategy: Update the most recently added tool call that's still being generated
138 // This handles the pattern: initial tool call with ID, then fragments without ID
139 existingStateIndex = toolCallStates.length - 1;
140
141 // Ensure we have at least one tool call to update
142 if (existingStateIndex < 0) {
143 existingStateIndex = -1; // Will create new tool call
144 }
145 }
146
147 const existingState =
148 existingStateIndex >= 0 ? toolCallStates[existingStateIndex] : undefined;
149
150 // Apply the delta to create an updated state (either updating existing or creating new)
151 const updatedState = addToolCallDeltaToState(toolCallDelta, existingState);
152
153 if (existingStateIndex >= 0) {
154 // Update existing tool call state in place
155 toolCallStates[existingStateIndex] = updatedState;
156 } else {
157 // Add new tool call state for a newly discovered tool call
158 toolCallStates.push(updatedState);
159 }
160}
161
162/**
163 * Handles incremental updates to tool calls during streaming responses.
164 * This function processes streaming deltas for tool calls, updating existing
165 * tool call states or creating new ones as needed. It uses ID-based matching
166 * to ensure tool call updates are applied to the correct tool call state.
167 *
168 * @param message - The streaming message chunk containing tool call deltas
169 * @param lastItem - The chat history item containing existing tool call states
170 */
171export function handleStreamingToolCallUpdates(
172 message: ChatMessage,
173 lastItem: ChatHistoryItemWithMessageId,
174): void {
175 if (
176 message.role === "assistant" &&
177 message.toolCalls?.length &&
178 lastItem.message.role === "assistant"
179 ) {
180 // Start with existing tool call states or empty array if none exist
181 const existingToolCallStates = lastItem.toolCallStates || [];
182 const updatedToolCallStates: ToolCallState[] = [...existingToolCallStates];
183
184 // Filter out duplicate edit/search-replace tool calls - only keep the first one
185 const filteredToolCalls = filterMultipleEditToolCalls(message.toolCalls);
186
187 // Process each filtered tool call delta, matching by ID to update the correct state
188 filteredToolCalls.forEach((toolCallDelta) => {
189 applyToolCallDelta(toolCallDelta, updatedToolCallStates);
190 });
191
192 // Replace the entire tool call states array with the updated version
193 lastItem.toolCallStates = updatedToolCallStates;
194
195 // Update the message's toolCalls array to reflect current tool call states
196 (lastItem.message as any).toolCalls = updatedToolCallStates.map(
197 (state) => state.toolCall,
198 );
199 }
200}
201
202// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
203// The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
204export type ChatHistoryItemWithMessageId = ChatHistoryItem & {
205 message: ChatMessage & { id: string };
206};
207
208type SessionState = {
209 lastSessionId?: string;
210 isSessionMetadataLoading: boolean;
211 allSessionMetadata: SessionMetadata[];
212 history: ChatHistoryItemWithMessageId[];
213 isStreaming: boolean;
214 title: string;
215 id: string;
216 streamAborter: AbortController;
217 mainEditorContentTrigger?: JSONContent | undefined;
218 symbols: FileSymbolMap;
219 mode: MessageModes;
220 isInEdit: boolean;
221 codeBlockApplyStates: {
222 states: ApplyState[];
223 curIndex: number;
224 };
225 newestToolbarPreviewForInput: Record<string, string>;
226 hasReasoningEnabled?: boolean;
227 isPruned?: boolean;
228 contextPercentage?: number;
229 inlineErrorMessage?: InlineErrorMessageType;
230 compactionLoading: Record<number, boolean>; // Track compaction loading by message index
231};
232
233const initialState: SessionState = {
234 isSessionMetadataLoading: false,
235 allSessionMetadata: [],
236 history: [],
237 isStreaming: false,
238 title: NEW_SESSION_TITLE,
239 id: uuidv4(),
240 streamAborter: new AbortController(),
241 symbols: {},
242 mode: "agent",
243 isInEdit: false,
244 codeBlockApplyStates: {
245 states: [],
246 curIndex: 0,
247 },
248 lastSessionId: undefined,
249 newestToolbarPreviewForInput: {},
250 compactionLoading: {},
251};
252
253export const sessionSlice = createSlice({
254 name: "session",
255 initialState,
256 reducers: {
257 addPromptCompletionPair: (
258 state,
259 { payload }: PayloadAction<PromptLog[]>,
260 ) => {
261 if (!state.history.length) {
262 return;
263 }
264
265 const lastMessage = state.history[state.history.length - 1];
266
267 lastMessage.promptLogs = lastMessage.promptLogs
268 ? lastMessage.promptLogs.concat(payload)
269 : payload;
270
271 // Inactive thinking for reasoning models when '</think>' tag is not received on request completion
272 if (lastMessage.reasoning?.active) {
273 lastMessage.reasoning.active = false;
274 lastMessage.reasoning.endAt = Date.now();
275 }
276 },
277 setActive: (state) => {
278 state.isStreaming = true;
279 },
280 setIsGatheringContext: (state, { payload }: PayloadAction<boolean>) => {
281 const curMessage = state.history.at(-1);
282 if (curMessage) {
283 curMessage.isGatheringContext = payload;
284 }
285 },
286 clearDanglingMessages: (state) => {
287 // This is used during cancellation
288 // After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing.
289 // The only thing allowed after the last assistant message that has either content or generated tool calls
290 // is a user or tool message
291 if (state.history.length < 2) {
292 return;
293 }
294
295 const lastUserOrToolIdx = findLastIndex(
296 state.history,
297 (item) => item.message.role === "tool" || item.message.role === "user",
298 );
299
300 let validAssistantMessageIdx = -1;
301 for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) {
302 const message = state.history[i];
303 const hasGeneratedMsg = message.toolCallStates?.some(
304 (toolCallState) => toolCallState.status !== "generating",
305 );
306 if (message.message.content || hasGeneratedMsg) {
307 validAssistantMessageIdx = i;
308 // Cancel any tool calls that are dangling and generated
309 if (message.toolCallStates) {
310 message.toolCallStates.forEach((toolCallState) => {
311 if (toolCallState.status === "generated") {
312 toolCallState.status = "canceled";
313 }
314 });
315 }
316 break;
317 }
318 }
319
320 if (validAssistantMessageIdx === -1) {
321 const lastMsg = state.history[lastUserOrToolIdx];
322 const lastRole = lastMsg.message.role as "user" | "tool";
323 if (lastRole === "user") {
324 state.mainEditorContentTrigger = lastMsg.editorState;
325 state.history = state.history.slice(0, lastUserOrToolIdx);
326 } else {
327 state.history = state.history.slice(0, lastUserOrToolIdx + 1);
328 }
329 } else {
330 state.history = state.history.slice(0, validAssistantMessageIdx + 1);
331 }
332 },
333 // Trigger value picked up by editor with isMainInput to set its content
334 setMainEditorContentTrigger: (
335 state,
336 action: PayloadAction<JSONContent | undefined>,
337 ) => {
338 state.mainEditorContentTrigger = action.payload;
339 },
340 updateFileSymbols: (state, action: PayloadAction<FileSymbolMap>) => {
341 state.symbols = {
342 ...state.symbols,
343 ...action.payload,
344 };
345 },
346 setContextItemsAtIndex: (
347 state,
348 {
349 payload: { index, contextItems },
350 }: PayloadAction<{
351 index: number;
352 contextItems: ChatHistoryItem["contextItems"];
353 }>,
354 ) => {
355 if (state.history[index]) {
356 state.history[index].contextItems = contextItems;
357 }
358 },
359 submitEditorAndInitAtIndex: (
360 state,
361 {
362 payload,
363 }: PayloadAction<{
364 index: number;
365 editorState: JSONContent;
366 }>,
367 ) => {
368 const { index, editorState } = payload;
369
370 if (state.history.length && index < state.history.length) {
371 // Resubmission - update input message, truncate history after resubmit with new empty response message
372 if (index % 2 === 1) {
373 console.warn(
374 "Corrupted history: resubmitting at odd index, shouldn't happen",
375 );
376 }
377 const historyItem = state.history[index];
378
379 historyItem.message.content = ""; // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming
380 historyItem.editorState = payload.editorState;
381 historyItem.contextItems = [];
382
383 state.history = state.history.slice(0, index + 1).concat({
384 message: {
385 id: uuidv4(),
386 role: "assistant",
387 content: "", // IMPORTANT - this is subsequently updated by response streaming
388 },
389 contextItems: [],
390 });
391 } else {
392 // New input/response messages
393 state.history = state.history.concat([
394 {
395 message: {
396 id: uuidv4(),
397 role: "user",
398 content: "", // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming
399 },
400 contextItems: [],
401 editorState,
402 },
403 {
404 message: {
405 id: uuidv4(),
406 role: "assistant",
407 content: "", // IMPORTANT - this is subsequently updated by response streaming
408 },
409 contextItems: [],
410 },
411 ]);
412 }
413
414 state.isStreaming = true;
415 },
416 truncateHistoryToMessage: (
417 state,
418 {
419 payload,
420 }: PayloadAction<{
421 index: number;
422 }>,
423 ) => {
424 const { index } = payload;
425
426 if (state.history.length && index < state.history.length) {
427 state.codeBlockApplyStates.curIndex = 0;
428 state.history = state.history.slice(0, index + 1).concat({
429 message: {
430 id: uuidv4(),
431 role: "assistant",
432 content: "", // IMPORTANT - this is subsequently updated by response streaming
433 },
434 contextItems: [],
435 });
436 state.inlineErrorMessage = undefined;
437 state.isPruned = false;
438 state.contextPercentage = undefined;
439 }
440 },
441 deleteMessage: (state, action: PayloadAction<number>) => {
442 // Deletes the current assistant message and the previous user message
443 state.history.splice(action.payload - 1, 2);
444 state.inlineErrorMessage = undefined;
445 state.isPruned = false;
446 state.contextPercentage = undefined;
447 },
448 deleteCompaction: (state, action: PayloadAction<number>) => {
449 // Removes the conversation summary from the specified message
450 const historyItem = state.history[action.payload];
451 if (historyItem?.conversationSummary) {
452 state.history[action.payload] = {
453 ...historyItem,
454 conversationSummary: undefined,
455 };
456 }
457 },
458 updateHistoryItemAtIndex: (
459 state,
460 {
461 payload,
462 }: PayloadAction<{
463 index: number;
464 updates: Partial<ChatHistoryItemWithMessageId>;
465 }>,
466 ) => {
467 const { index, updates } = payload;
468 if (index !== 0 && !state.history[index]) {
469 console.error(
470 `attempting to update history item at nonexistent index ${index}`,
471 updates,
472 );
473 return;
474 }
475 state.history[index] = {
476 ...state.history[index],
477 ...updates,
478 };
479 },
480 addContextItemsAtIndex: (
481 state,
482 {
483 payload,
484 }: PayloadAction<{
485 index: number;
486 contextItems: ContextItemWithId[];
487 }>,
488 ) => {
489 const historyItem = state.history[payload.index];
490
491 if (!historyItem) {
492 return;
493 }
494
495 historyItem.contextItems = [
496 ...historyItem.contextItems,
497 ...payload.contextItems,
498 ];
499 },
500 setAppliedRulesAtIndex: (
501 state,
502 {
503 payload,
504 }: PayloadAction<{
505 index: number;
506 appliedRules: RuleWithSource[];
507 }>,
508 ) => {
509 if (state.history[payload.index]) {
510 state.history[payload.index].appliedRules = payload.appliedRules;
511 }
512 },
513 setInactive: (state) => {
514 const curMessage = state.history.at(-1);
515
516 if (curMessage) {
517 curMessage.isGatheringContext = false;
518 }
519
520 state.isStreaming = false;
521 },
522 abortStream: (state) => {
523 state.streamAborter.abort();
524 state.streamAborter = new AbortController();
525 },
526 streamUpdate: (state, action: PayloadAction<ChatMessage[]>) => {
527 if (state.history.length) {
528 for (const message of action.payload) {
529 let lastItem = state.history[state.history.length - 1];
530 let lastMessage = lastItem.message;
531
532 if (message.role === "thinking" && message.redactedThinking) {
533 state.history.push({
534 message: {
535 role: "thinking",
536 content: "internal reasoning is hidden due to safety reasons",
537 redactedThinking: message.redactedThinking,
538 id: uuidv4(),
539 },
540 contextItems: [],
541 });
542 continue;
543 }
544
545 const messageContent = message.content
546 ? renderChatMessage(message)
547 : "";
548
549 // OpenAI-compatible models in agent mode sometimes send
550 // all of their data in one message, so we handle that case early.
551 if (messageContent) {
552 const thinkMatches = messageContent.match(
553 /<think>([\s\S]*)<\/think>([\s\S]*)/,
554 );
555 if (thinkMatches) {
556 // The order that they seem to consistently use is:
557 //
558 // <think>Thinking text</think>
559 // Text to show to the user
560
561 lastItem.reasoning = {
562 text: thinkMatches[1].trim(),
563 startAt: Date.now(),
564 endAt: Date.now(),
565 active: false,
566 };
567
568 // This is the chat message that we should show to the user.
569 // We always need to push this even if it is empty,
570 // because we cannot attach tool calls to a Thinking message.
571 // That would break `messageHasToolCallId`.
572 state.history.push({
573 message: {
574 role: "assistant",
575 content: thinkMatches[2].trim(),
576 id: uuidv4(),
577 },
578 contextItems: [],
579 });
580 lastItem = state.history[state.history.length - 1];
581 lastMessage = lastItem.message;
582
583 handleToolCallsInMessage(message, lastItem);
584
585 return;
586 }
587 }
588
589 // The remainder of this function handles streaming messages
590 if (
591 lastMessage.role !== message.role ||
592 message.role === "tool" // Tool messages should always create new messages
593 ) {
594 // Create a new message
595 const historyItem: ChatHistoryItemWithMessageId = {
596 message: {
597 ...message,
598 content: "", // Start with empty content, let accumulation logic handle it
599 id: uuidv4(),
600 },
601 contextItems: [],
602 };
603 handleToolCallsInMessage(message, historyItem);
604 state.history.push(historyItem);
605 lastItem = state.history[state.history.length - 1];
606 lastMessage = lastItem.message;
607 }
608
609 // Add to the existing message
610 if (messageContent) {
611 if (messageContent.includes("<think>")) {
612 lastItem.reasoning = {
613 startAt: Date.now(),
614 active: true,
615 text: messageContent.replace("<think>", "").trim(),
616 };
617 } else if (
618 lastItem.reasoning?.active &&
619 messageContent.includes("</think>")
620 ) {
621 const [reasoningEnd, answerStart] =
622 messageContent.split("</think>");
623 lastItem.reasoning.text += reasoningEnd.trimEnd();
624 lastItem.reasoning.active = false;
625 lastItem.reasoning.endAt = Date.now();
626 lastMessage.content += answerStart.trimStart();
627 } else if (lastItem.reasoning?.active) {
628 if (
629 lastItem.reasoning.text.length > 0 ||
630 messageContent.trim().length > 0
631 ) {
632 lastItem.reasoning.text += messageContent;
633 }
634 } else {
635 // Note this only works because new message above
636 // was already rendered from parts to string
637 if (
638 lastMessage.content.length > 0 ||
639 messageContent.trim().length > 0
640 ) {
641 lastMessage.content += messageContent;
642 }
643 }
644 } else if (message.role === "thinking" && message.signature) {
645 if (lastMessage.role === "thinking") {
646 lastMessage.signature = message.signature;
647 }
648 } else if (
649 message.role === "assistant" &&
650 message.toolCalls?.length &&
651 lastMessage.role === "assistant"
652 ) {
653 handleStreamingToolCallUpdates(message, lastItem);
654 }
655 }
656 }
657 },
658 newSession: (state, { payload }: PayloadAction<Session | undefined>) => {
659 state.lastSessionId = state.id;
660
661 state.streamAborter.abort();
662 state.streamAborter = new AbortController();
663
664 state.isStreaming = false;
665 state.symbols = {};
666
667 state.inlineErrorMessage = undefined;
668 state.isPruned = false;
669 state.contextPercentage = undefined;
670
671 if (payload) {
672 state.history = payload.history as any;
673 state.title = payload.title;
674 state.id = payload.sessionId;
675 } else {
676 state.history = [];
677 state.title = NEW_SESSION_TITLE;
678 state.id = uuidv4();
679 }
680 },
681 updateSessionTitle: (state, { payload }: PayloadAction<string>) => {
682 state.title = payload;
683 },
684 setIsSessionMetadataLoading: (
685 state,
686 { payload }: PayloadAction<boolean>,
687 ) => {
688 state.isSessionMetadataLoading = payload;
689 },
690 setAllSessionMetadata: (
691 state,
692 { payload }: PayloadAction<SessionMetadata[]>,
693 ) => {
694 state.allSessionMetadata = payload;
695 },
696 //////////////////////////////////////////////////////////////////////////////////
697 // These are for optimistic session metadata updates, especially for History page
698 addSessionMetadata: (
699 state,
700 { payload }: PayloadAction<SessionMetadata>,
701 ) => {
702 state.allSessionMetadata = [...state.allSessionMetadata, payload];
703 },
704 updateSessionMetadata: (
705 state,
706 {
707 payload,
708 }: PayloadAction<
709 {
710 sessionId: string;
711 } & Partial<SessionMetadata>
712 >,
713 ) => {
714 state.allSessionMetadata = state.allSessionMetadata.map((session) =>
715 session.sessionId === payload.sessionId
716 ? {
717 ...session,
718 ...payload,
719 }
720 : session,
721 );
722 if (payload.title && payload.sessionId === state.id) {
723 state.title = payload.title;
724 }
725 },
726 deleteSessionMetadata: (state, { payload }: PayloadAction<string>) => {
727 // Note, should not be allowed to delete current session from chat session
728 state.allSessionMetadata = state.allSessionMetadata.filter(
729 (session) => session.sessionId !== payload,
730 );
731 },
732 //////////////////////////////////////////////////////////////////////////////////
733 addHighlightedCode: (
734 state,
735 {
736 payload,
737 }: PayloadAction<{ rangeInFileWithContents: any; edit: boolean }>,
738 ) => {
739 let contextItems =
740 state.history[state.history.length - 1].contextItems ?? [];
741
742 contextItems = contextItems.map((item) => {
743 return { ...item, editing: false };
744 });
745
746 const { relativePathOrBasename } = findUriInDirs(
747 payload.rangeInFileWithContents.filepath,
748 window.workspacePaths ?? [],
749 );
750 const fileName = getUriPathBasename(
751 payload.rangeInFileWithContents.filepath,
752 );
753
754 const lineNums = `(${
755 payload.rangeInFileWithContents.range.start.line + 1
756 }-${payload.rangeInFileWithContents.range.end.line + 1})`;
757
758 contextItems.push({
759 name: `${fileName} ${lineNums}`,
760 description: relativePathOrBasename,
761 id: {
762 providerTitle: "code",
763 itemId: uuidv4(),
764 },
765 content: payload.rangeInFileWithContents.contents,
766 editing: true,
767 editable: true,
768 uri: {
769 type: "file",
770 value: payload.rangeInFileWithContents.filepath,
771 },
772 });
773
774 state.history[state.history.length - 1].contextItems = contextItems;
775 },
776 updateApplyState: (state, { payload }: PayloadAction<ApplyState>) => {
777 const applyState = state.codeBlockApplyStates.states.find(
778 (state) => state.streamId === payload.streamId,
779 );
780
781 if (!applyState) {
782 state.codeBlockApplyStates.states.push(payload);
783 } else {
784 applyState.status = payload.status ?? applyState.status;
785 applyState.numDiffs = payload.numDiffs ?? applyState.numDiffs;
786 applyState.filepath = payload.filepath ?? applyState.filepath;
787 applyState.fileContent = payload.fileContent ?? applyState.fileContent;
788 applyState.originalFileContent =
789 payload.originalFileContent ?? applyState.originalFileContent;
790 }
791
792 if (payload.status === "done") {
793 state.codeBlockApplyStates.curIndex++;
794 }
795 },
796 resetNextCodeBlockToApplyIndex: (state) => {
797 state.codeBlockApplyStates.curIndex = 0;
798 },
799
800 // TOOL CALL STATE
801 setToolGenerated: (
802 state,
803 action: PayloadAction<{
804 toolCallId: string;
805 tools: Tool[];
806 }>,
807 ) => {
808 const toolCallState = findToolCallById(
809 state.history,
810 action.payload.toolCallId,
811 );
812
813 if (toolCallState) {
814 toolCallState.status = "generated";
815
816 const tool = action.payload.tools.find(
817 (t) => t.function.name === toolCallState.toolCall.function.name,
818 );
819 if (tool) {
820 toolCallState.tool = tool;
821 }
822 }
823 },
824 updateToolCallOutput: (
825 state,
826 action: PayloadAction<{
827 toolCallId: string;
828 contextItems: ContextItem[];
829 }>,
830 ) => {
831 // Update tool call state and corresponding tool output message
832 const toolCallState = findToolCallById(
833 state.history,
834 action.payload.toolCallId,
835 );
836 if (toolCallState) {
837 toolCallState.output = action.payload.contextItems;
838 }
839 const toolItem = findChatHistoryItemByToolCallId(
840 state.history,
841 action.payload.toolCallId,
842 );
843 if (toolItem) {
844 toolItem.message.content = renderContextItems(
845 action.payload.contextItems,
846 );
847 toolItem.contextItems = action.payload.contextItems.map((item) =>
848 toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId),
849 );
850 }
851 },
852 setToolCallArgs: (
853 state,
854 action: PayloadAction<{
855 toolCallId: string;
856 newArgs: Record<string, any>;
857 }>,
858 ) => {
859 const toolCallState = findToolCallById(
860 state.history,
861 action.payload.toolCallId,
862 );
863 if (toolCallState) {
864 toolCallState.parsedArgs = action.payload.newArgs;
865 }
866 },
867 cancelToolCall: (
868 state,
869 action: PayloadAction<{
870 toolCallId: string;
871 }>,
872 ) => {
873 const toolCallState = findToolCallById(
874 state.history,
875 action.payload.toolCallId,
876 );
877 if (toolCallState) {
878 toolCallState.status = "canceled";
879 }
880 },
881 errorToolCall: (
882 state,
883 action: PayloadAction<{
884 toolCallId: string;
885 }>,
886 ) => {
887 const toolCallState = findToolCallById(
888 state.history,
889 action.payload.toolCallId,
890 );
891 if (toolCallState) {
892 toolCallState.status = "errored";
893 }
894 },
895 acceptToolCall: (
896 state,
897 action: PayloadAction<{
898 toolCallId: string;
899 }>,
900 ) => {
901 const toolCallState = findToolCallById(
902 state.history,
903 action.payload.toolCallId,
904 );
905 if (toolCallState) {
906 toolCallState.status = "done";
907 }
908 },
909 setToolCallCalling: (
910 state,
911 action: PayloadAction<{
912 toolCallId: string;
913 }>,
914 ) => {
915 const toolCallState = findToolCallById(
916 state.history,
917 action.payload.toolCallId,
918 );
919 if (toolCallState) {
920 toolCallState.status = "calling";
921 }
922 },
923 setMode: (state, action: PayloadAction<MessageModes>) => {
924 state.mode = action.payload;
925 },
926 setIsInEdit: (state, action: PayloadAction<boolean>) => {
927 state.isInEdit = action.payload;
928 },
929 setHasReasoningEnabled: (state, action: PayloadAction<boolean>) => {
930 state.hasReasoningEnabled = action.payload;
931 },
932 setNewestToolbarPreviewForInput: (
933 state,
934 {
935 payload,
936 }: PayloadAction<{
937 inputId: string;
938 contextItemId: string;
939 }>,
940 ) => {
941 state.newestToolbarPreviewForInput[payload.inputId] =
942 payload.contextItemId;
943 },
944 setCompactionLoading: (
945 state,
946 action: PayloadAction<{ index: number; loading: boolean }>,
947 ) => {
948 const { index, loading } = action.payload;
949 if (loading) {
950 state.compactionLoading[index] = true;
951 } else {
952 delete state.compactionLoading[index];
953 }
954 },
955 setInlineErrorMessage: (
956 state,
957 action: PayloadAction<SessionState["inlineErrorMessage"]>,
958 ) => {
959 state.inlineErrorMessage = action.payload;
960 },
961 setIsPruned: (state, action: PayloadAction<boolean>) => {
962 state.isPruned = action.payload;
963 },
964 setContextPercentage: (state, action: PayloadAction<number>) => {
965 state.contextPercentage = action.payload;
966 },
967 },
968 selectors: {
969 selectIsGatheringContext: (state) => {
970 const curHistoryItem = state.history.at(-1);
971 return curHistoryItem?.isGatheringContext || false;
972 },
973 },
974 extraReducers: (builder) => {
975 addPassthroughCases(builder, [streamResponseThunk]);
976 },
977});
978
979function addPassthroughCases(
980 builder: ActionReducerMapBuilder<SessionState>,
981 thunks: AsyncThunk<any, any, any>[],
982) {
983 thunks.forEach((thunk) => {
984 builder
985 .addCase(thunk.fulfilled, (_state, _action) => {})
986 .addCase(thunk.rejected, (_state, _action) => {})
987 .addCase(thunk.pending, (_state, _action) => {});
988 });
989}
990
991export const selectApplyStateByStreamId = createSelector(
992 [
993 (state: RootState) => state.session.codeBlockApplyStates.states,
994 (_state: RootState, streamId?: string) => streamId,
995 ],
996 (states, streamId) => {
997 return states.find((state) => state.streamId === streamId);
998 },
999);
1000
1001export const selectApplyStateByToolCallId = createSelector(
1002 [
1003 (state: RootState) => state.session.codeBlockApplyStates.states,
1004 (_state: RootState, toolCallId?: string) => toolCallId,
1005 ],
1006 (states, toolCallId) => {
1007 if (toolCallId) {
1008 return states.find((state) => state.toolCallId === toolCallId);
1009 }
1010 },
1011);
1012
1013export const {
1014 updateFileSymbols,
1015 setContextItemsAtIndex,
1016 addContextItemsAtIndex,
1017 setAppliedRulesAtIndex,
1018 setInactive,
1019 streamUpdate,
1020 newSession,
1021 updateSessionTitle,
1022 addHighlightedCode,
1023 addPromptCompletionPair,
1024 setActive,
1025 submitEditorAndInitAtIndex,
1026 truncateHistoryToMessage,
1027 updateHistoryItemAtIndex,
1028 clearDanglingMessages,
1029 setMainEditorContentTrigger,
1030 deleteMessage,
1031 deleteCompaction,
1032 setIsGatheringContext,
1033 resetNextCodeBlockToApplyIndex,
1034 updateApplyState,
1035 abortStream,
1036 setToolCallCalling,
1037 cancelToolCall,
1038 errorToolCall,
1039 acceptToolCall,
1040 setToolGenerated,
1041 updateToolCallOutput,
1042 setToolCallArgs,
1043 setMode,
1044 setIsSessionMetadataLoading,
1045 setAllSessionMetadata,
1046 addSessionMetadata,
1047 updateSessionMetadata,
1048 deleteSessionMetadata,
1049 setNewestToolbarPreviewForInput,
1050 setIsInEdit,
1051 setHasReasoningEnabled,
1052 setInlineErrorMessage,
1053 setIsPruned,
1054 setContextPercentage,
1055 setCompactionLoading,
1056} = sessionSlice.actions;
1057
1058export const { selectIsGatheringContext } = sessionSlice.selectors;
1059
1060export default sessionSlice.reducer;