Elffuss BraidHub

kikocis/continue public

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