Elffuss BraidHub

kikocis/continue public

22e692d80113 · 32.0 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 }
788
789 if (payload.status === "done") {
790 state.codeBlockApplyStates.curIndex++;
791 }
792 },
793 resetNextCodeBlockToApplyIndex: (state) => {
794 state.codeBlockApplyStates.curIndex = 0;
795 },
796
797 // TOOL CALL STATE
798 setToolGenerated: (
799 state,
800 action: PayloadAction<{
801 toolCallId: string;
802 tools: Tool[];
803 }>,
804 ) => {
805 const toolCallState = findToolCallById(
806 state.history,
807 action.payload.toolCallId,
808 );
809
810 if (toolCallState) {
811 toolCallState.status = "generated";
812
813 const tool = action.payload.tools.find(
814 (t) => t.function.name === toolCallState.toolCall.function.name,
815 );
816 if (tool) {
817 toolCallState.tool = tool;
818 }
819 }
820 },
821 updateToolCallOutput: (
822 state,
823 action: PayloadAction<{
824 toolCallId: string;
825 contextItems: ContextItem[];
826 }>,
827 ) => {
828 // Update tool call state and corresponding tool output message
829 const toolCallState = findToolCallById(
830 state.history,
831 action.payload.toolCallId,
832 );
833 if (toolCallState) {
834 toolCallState.output = action.payload.contextItems;
835 }
836 const toolItem = findChatHistoryItemByToolCallId(
837 state.history,
838 action.payload.toolCallId,
839 );
840 if (toolItem) {
841 toolItem.message.content = renderContextItems(
842 action.payload.contextItems,
843 );
844 toolItem.contextItems = action.payload.contextItems.map((item) =>
845 toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId),
846 );
847 }
848 },
849 cancelToolCall: (
850 state,
851 action: PayloadAction<{
852 toolCallId: string;
853 }>,
854 ) => {
855 const toolCallState = findToolCallById(
856 state.history,
857 action.payload.toolCallId,
858 );
859 if (toolCallState) {
860 toolCallState.status = "canceled";
861 }
862 },
863 errorToolCall: (
864 state,
865 action: PayloadAction<{
866 toolCallId: string;
867 }>,
868 ) => {
869 const toolCallState = findToolCallById(
870 state.history,
871 action.payload.toolCallId,
872 );
873 if (toolCallState) {
874 toolCallState.status = "errored";
875 }
876 },
877 acceptToolCall: (
878 state,
879 action: PayloadAction<{
880 toolCallId: string;
881 }>,
882 ) => {
883 const toolCallState = findToolCallById(
884 state.history,
885 action.payload.toolCallId,
886 );
887 if (toolCallState) {
888 toolCallState.status = "done";
889 }
890 },
891 setToolCallCalling: (
892 state,
893 action: PayloadAction<{
894 toolCallId: string;
895 }>,
896 ) => {
897 const toolCallState = findToolCallById(
898 state.history,
899 action.payload.toolCallId,
900 );
901 if (toolCallState) {
902 toolCallState.status = "calling";
903 }
904 },
905 setMode: (state, action: PayloadAction<MessageModes>) => {
906 state.mode = action.payload;
907 },
908 setIsInEdit: (state, action: PayloadAction<boolean>) => {
909 state.isInEdit = action.payload;
910 },
911 setHasReasoningEnabled: (state, action: PayloadAction<boolean>) => {
912 state.hasReasoningEnabled = action.payload;
913 },
914 setNewestToolbarPreviewForInput: (
915 state,
916 {
917 payload,
918 }: PayloadAction<{
919 inputId: string;
920 contextItemId: string;
921 }>,
922 ) => {
923 state.newestToolbarPreviewForInput[payload.inputId] =
924 payload.contextItemId;
925 },
926 setCompactionLoading: (
927 state,
928 action: PayloadAction<{ index: number; loading: boolean }>,
929 ) => {
930 const { index, loading } = action.payload;
931 if (loading) {
932 state.compactionLoading[index] = true;
933 } else {
934 delete state.compactionLoading[index];
935 }
936 },
937 setInlineErrorMessage: (
938 state,
939 action: PayloadAction<SessionState["inlineErrorMessage"]>,
940 ) => {
941 state.inlineErrorMessage = action.payload;
942 },
943 setIsPruned: (state, action: PayloadAction<boolean>) => {
944 state.isPruned = action.payload;
945 },
946 setContextPercentage: (state, action: PayloadAction<number>) => {
947 state.contextPercentage = action.payload;
948 },
949 },
950 selectors: {
951 selectIsGatheringContext: (state) => {
952 const curHistoryItem = state.history.at(-1);
953 return curHistoryItem?.isGatheringContext || false;
954 },
955 },
956 extraReducers: (builder) => {
957 addPassthroughCases(builder, [streamResponseThunk]);
958 },
959});
960
961function addPassthroughCases(
962 builder: ActionReducerMapBuilder<SessionState>,
963 thunks: AsyncThunk<any, any, any>[],
964) {
965 thunks.forEach((thunk) => {
966 builder
967 .addCase(thunk.fulfilled, (_state, _action) => {})
968 .addCase(thunk.rejected, (_state, _action) => {})
969 .addCase(thunk.pending, (_state, _action) => {});
970 });
971}
972
973export const selectApplyStateByStreamId = createSelector(
974 [
975 (state: RootState) => state.session.codeBlockApplyStates.states,
976 (_state: RootState, streamId?: string) => streamId,
977 ],
978 (states, streamId) => {
979 return states.find((state) => state.streamId === streamId);
980 },
981);
982
983export const selectApplyStateByToolCallId = createSelector(
984 [
985 (state: RootState) => state.session.codeBlockApplyStates.states,
986 (_state: RootState, toolCallId?: string) => toolCallId,
987 ],
988 (states, toolCallId) => {
989 if (toolCallId) {
990 return states.find((state) => state.toolCallId === toolCallId);
991 }
992 },
993);
994
995export const {
996 updateFileSymbols,
997 setContextItemsAtIndex,
998 addContextItemsAtIndex,
999 setAppliedRulesAtIndex,
1000 setInactive,
1001 streamUpdate,
1002 newSession,
1003 updateSessionTitle,
1004 addHighlightedCode,
1005 addPromptCompletionPair,
1006 setActive,
1007 submitEditorAndInitAtIndex,
1008 truncateHistoryToMessage,
1009 updateHistoryItemAtIndex,
1010 clearDanglingMessages,
1011 setMainEditorContentTrigger,
1012 deleteMessage,
1013 deleteCompaction,
1014 setIsGatheringContext,
1015 resetNextCodeBlockToApplyIndex,
1016 updateApplyState,
1017 abortStream,
1018 setToolCallCalling,
1019 cancelToolCall,
1020 errorToolCall,
1021 acceptToolCall,
1022 setToolGenerated,
1023 updateToolCallOutput,
1024 setMode,
1025 setIsSessionMetadataLoading,
1026 setAllSessionMetadata,
1027 addSessionMetadata,
1028 updateSessionMetadata,
1029 deleteSessionMetadata,
1030 setNewestToolbarPreviewForInput,
1031 setIsInEdit,
1032 setHasReasoningEnabled,
1033 setInlineErrorMessage,
1034 setIsPruned,
1035 setContextPercentage,
1036 setCompactionLoading,
1037} = sessionSlice.actions;
1038
1039export const { selectIsGatheringContext } = sessionSlice.selectors;
1040
1041export default sessionSlice.reducer;