Elffuss BraidHub

kikocis/continue public

main · 32.7 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 BaseSessionMetadata,
22 ThinkingChatMessage,
23 Tool,
24 ToolCallDelta,
25 ToolCallState,
26} from "core";
27import type { RemoteSessionMetadata } from "core/control-plane/client";
28import { BuiltInToolNames } from "core/tools/builtIn";
29import { NEW_SESSION_TITLE } from "core/util/constants";
30import {
31 renderChatMessage,
32 renderContextItems,
33} from "core/util/messageContent";
34import { findUriInDirs, getUriPathBasename } from "core/util/uri";
35import { findLastIndex } from "lodash";
36import { v4 as uuidv4 } from "uuid";
37import { type InlineErrorMessageType } from "../../components/mainInput/InlineErrorMessage";
38import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/utils";
39import { addToolCallDeltaToState } from "../../util/toolCallState";
40import { RootState } from "../store";
41import { streamResponseThunk } from "../thunks/streamResponse";
42import { findChatHistoryItemByToolCallId, findToolCallById } from "../util";
43
44/**
45 * Helper function to filter out duplicate edit/search-replace tool calls.
46 * Only keeps the first occurrence of edit tools.
47 *
48 * We don't support multiple parallel apply calls - see tool definitions for
49 * instructions we provide to models to prevent this behavior.
50 */
51function filterMultipleEditToolCalls(
52 toolCalls: ToolCallDelta[],
53): ToolCallDelta[] {
54 const editToolNames = [BuiltInToolNames.EditExistingFile];
55 let hasSeenEditTool = false;
56
57 return toolCalls.filter((toolCall) => {
58 const isEditTool = editToolNames.includes(toolCall.function?.name as any);
59
60 if (isEditTool) {
61 if (hasSeenEditTool) {
62 return false; // Skip this duplicate edit tool
63 }
64 hasSeenEditTool = true;
65 }
66
67 return true;
68 });
69}
70
71/**
72 * Initializes tool call states for a new message containing tool calls.
73 * This function is called when we receive a complete message with tool calls,
74 * typically in non-streaming scenarios or when processing the first chunk
75 * of a streaming message that contains tool calls.
76 *
77 * @param message - The chat message containing tool calls to process
78 * @param lastItem - The chat history item to attach tool call states to
79 */
80export function handleToolCallsInMessage(
81 message: ChatMessage,
82 lastItem: ChatHistoryItemWithMessageId,
83): void {
84 if (
85 (message.role === "assistant" || message.role === "thinking") &&
86 message.toolCalls?.length
87 ) {
88 // Filter out duplicate edit/search-replace tool calls - only keep the first one
89 const filteredToolCalls = filterMultipleEditToolCalls(message.toolCalls);
90
91 // Initialize tool call states for each filtered tool call in the message
92 // Each tool call gets its own state to track generation/execution progress
93 lastItem.toolCallStates = filteredToolCalls.map((toolCallDelta) =>
94 addToolCallDeltaToState(toolCallDelta, undefined),
95 );
96
97 // Update the message's toolCalls array to reflect the processed tool calls
98 // We can safely cast because we verified the role above
99 const curMessage = lastItem.message as
100 | AssistantChatMessage
101 | ThinkingChatMessage;
102 curMessage.toolCalls = lastItem.toolCallStates.map(
103 (state) => state.toolCall,
104 );
105 }
106}
107
108/**
109 * Applies a single tool call delta to the tool call states array.
110 *
111 * This function handles the core logic for OpenAI-style tool call streaming where:
112 * - Initial tool calls come with full details (ID, name, arguments)
113 * - Subsequent argument fragments come without IDs and need to update the most recent tool call
114 * - Multiple parallel tool calls can be streamed simultaneously
115 *
116 * @param toolCallDelta - The incoming tool call delta from the LLM stream
117 * @param toolCallStates - Array of existing tool call states (modified in place)
118 */
119function applyToolCallDelta(
120 toolCallDelta: ToolCallDelta,
121 toolCallStates: ToolCallState[],
122): void {
123 // Find existing state by matching toolCallId - this ensures we update
124 // the correct tool call even when multiple tool calls are being streamed
125 let existingStateIndex = -1;
126
127 if (toolCallDelta.id) {
128 // Tool call has an ID - find by exact match
129 // This handles: new tool calls or explicit updates to existing ones
130 existingStateIndex = toolCallStates.findIndex(
131 (state) => state.toolCallId === toolCallDelta.id,
132 );
133 } else {
134 // No ID in delta (common in OpenAI streaming fragments)
135 // Strategy: Update the most recently added tool call that's still being generated
136 // This handles the pattern: initial tool call with ID, then fragments without ID
137 existingStateIndex = toolCallStates.length - 1;
138
139 // Ensure we have at least one tool call to update
140 if (existingStateIndex < 0) {
141 existingStateIndex = -1; // Will create new tool call
142 }
143 }
144
145 const existingState =
146 existingStateIndex >= 0 ? toolCallStates[existingStateIndex] : undefined;
147
148 // Apply the delta to create an updated state (either updating existing or creating new)
149 const updatedState = addToolCallDeltaToState(toolCallDelta, existingState);
150
151 if (existingStateIndex >= 0) {
152 // Update existing tool call state in place
153 toolCallStates[existingStateIndex] = updatedState;
154 } else {
155 // Add new tool call state for a newly discovered tool call
156 toolCallStates.push(updatedState);
157 }
158}
159
160/**
161 * Handles incremental updates to tool calls during streaming responses.
162 * This function processes streaming deltas for tool calls, updating existing
163 * tool call states or creating new ones as needed. It uses ID-based matching
164 * to ensure tool call updates are applied to the correct tool call state.
165 *
166 * @param message - The streaming message chunk containing tool call deltas
167 * @param lastItem - The chat history item containing existing tool call states
168 */
169export function handleStreamingToolCallUpdates(
170 message: ChatMessage,
171 lastItem: ChatHistoryItemWithMessageId,
172): void {
173 if (
174 message.role === "assistant" &&
175 message.toolCalls?.length &&
176 lastItem.message.role === "assistant"
177 ) {
178 // Start with existing tool call states or empty array if none exist
179 const existingToolCallStates = lastItem.toolCallStates || [];
180 const updatedToolCallStates: ToolCallState[] = [...existingToolCallStates];
181
182 // Filter out duplicate edit/search-replace tool calls - only keep the first one
183 const filteredToolCalls = filterMultipleEditToolCalls(message.toolCalls);
184
185 // Process each filtered tool call delta, matching by ID to update the correct state
186 filteredToolCalls.forEach((toolCallDelta) => {
187 applyToolCallDelta(toolCallDelta, updatedToolCallStates);
188 });
189
190 // Replace the entire tool call states array with the updated version
191 lastItem.toolCallStates = updatedToolCallStates;
192
193 // Update the message's toolCalls array to reflect current tool call states
194 (lastItem.message as any).toolCalls = updatedToolCallStates.map(
195 (state) => state.toolCall,
196 );
197 }
198}
199
200// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
201// The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
202export type ChatHistoryItemWithMessageId = ChatHistoryItem & {
203 message: ChatMessage & { id: string };
204};
205
206type SessionState = {
207 lastSessionId?: string;
208 isSessionMetadataLoading: boolean;
209 allSessionMetadata: (BaseSessionMetadata | RemoteSessionMetadata)[];
210 history: ChatHistoryItemWithMessageId[];
211 isStreaming: boolean;
212 title: string;
213 id: string;
214 streamAborter: AbortController;
215 mainEditorContentTrigger?: JSONContent | undefined;
216 symbols: FileSymbolMap;
217 mode: MessageModes;
218 isInEdit: boolean;
219 codeBlockApplyStates: {
220 states: ApplyState[];
221 curIndex: number;
222 };
223 newestToolbarPreviewForInput: Record<string, string>;
224 hasReasoningEnabled?: boolean;
225 isPruned?: boolean;
226 contextPercentage?: number;
227 inlineErrorMessage?: InlineErrorMessageType;
228 compactionLoading: Record<number, boolean>; // Track compaction loading by message index
229};
230
231const initialState: SessionState = {
232 isSessionMetadataLoading: false,
233 allSessionMetadata: [],
234 history: [],
235 isStreaming: false,
236 title: NEW_SESSION_TITLE,
237 id: uuidv4(),
238 streamAborter: new AbortController(),
239 symbols: {},
240 mode: "agent",
241 isInEdit: false,
242 codeBlockApplyStates: {
243 states: [],
244 curIndex: 0,
245 },
246 lastSessionId: undefined,
247 newestToolbarPreviewForInput: {},
248 compactionLoading: {},
249};
250
251export const sessionSlice = createSlice({
252 name: "session",
253 initialState,
254 reducers: {
255 addPromptCompletionPair: (
256 state,
257 { payload }: PayloadAction<PromptLog[]>,
258 ) => {
259 if (!state.history.length) {
260 return;
261 }
262
263 const lastMessage = state.history[state.history.length - 1];
264
265 lastMessage.promptLogs = lastMessage.promptLogs
266 ? lastMessage.promptLogs.concat(payload)
267 : payload;
268
269 // Inactive thinking for reasoning models when '</think>' tag is not received on request completion
270 if (lastMessage.reasoning?.active) {
271 lastMessage.reasoning.active = false;
272 lastMessage.reasoning.endAt = Date.now();
273 }
274 },
275 setActive: (state) => {
276 state.isStreaming = true;
277 },
278 setIsGatheringContext: (state, { payload }: PayloadAction<boolean>) => {
279 const curMessage = state.history.at(-1);
280 if (curMessage) {
281 curMessage.isGatheringContext = payload;
282 }
283 },
284 clearDanglingMessages: (state) => {
285 // This is used during cancellation
286 // After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing.
287 // The only thing allowed after the last assistant message that has either content or generated tool calls
288 // is a user or tool message
289 if (state.history.length < 2) {
290 return;
291 }
292
293 const lastUserOrToolIdx = findLastIndex(
294 state.history,
295 (item) => item.message.role === "tool" || item.message.role === "user",
296 );
297
298 let validAssistantMessageIdx = -1;
299 for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) {
300 const message = state.history[i];
301 const hasGeneratedMsg = message.toolCallStates?.some(
302 (toolCallState) => toolCallState.status !== "generating",
303 );
304 if (message.message.content || hasGeneratedMsg) {
305 validAssistantMessageIdx = i;
306 // Cancel any tool calls that are dangling and generated
307 if (message.toolCallStates) {
308 message.toolCallStates.forEach((toolCallState) => {
309 if (toolCallState.status === "generated") {
310 toolCallState.status = "canceled";
311 }
312 });
313 }
314 break;
315 }
316 }
317
318 if (validAssistantMessageIdx === -1) {
319 const lastMsg = state.history[lastUserOrToolIdx];
320 const lastRole = lastMsg.message.role as "user" | "tool";
321 if (lastRole === "user") {
322 state.mainEditorContentTrigger = lastMsg.editorState;
323 state.history = state.history.slice(0, lastUserOrToolIdx);
324 } else {
325 state.history = state.history.slice(0, lastUserOrToolIdx + 1);
326 }
327 } else {
328 state.history = state.history.slice(0, validAssistantMessageIdx + 1);
329 }
330 },
331 // Trigger value picked up by editor with isMainInput to set its content
332 setMainEditorContentTrigger: (
333 state,
334 action: PayloadAction<JSONContent | undefined>,
335 ) => {
336 state.mainEditorContentTrigger = action.payload;
337 },
338 updateFileSymbols: (state, action: PayloadAction<FileSymbolMap>) => {
339 state.symbols = {
340 ...state.symbols,
341 ...action.payload,
342 };
343 },
344 setContextItemsAtIndex: (
345 state,
346 {
347 payload: { index, contextItems },
348 }: PayloadAction<{
349 index: number;
350 contextItems: ChatHistoryItem["contextItems"];
351 }>,
352 ) => {
353 if (state.history[index]) {
354 state.history[index].contextItems = contextItems;
355 }
356 },
357 submitEditorAndInitAtIndex: (
358 state,
359 {
360 payload,
361 }: PayloadAction<{
362 index: number;
363 editorState: JSONContent;
364 }>,
365 ) => {
366 const { index, editorState } = payload;
367
368 if (state.history.length && index < state.history.length) {
369 // Resubmission - update input message, truncate history after resubmit with new empty response message
370 if (index % 2 === 1) {
371 console.warn(
372 "Corrupted history: resubmitting at odd index, shouldn't happen",
373 );
374 }
375 const historyItem = state.history[index];
376
377 historyItem.message.content = ""; // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming
378 historyItem.editorState = payload.editorState;
379 historyItem.contextItems = [];
380
381 state.history = state.history.slice(0, index + 1).concat({
382 message: {
383 id: uuidv4(),
384 role: "assistant",
385 content: "", // IMPORTANT - this is subsequently updated by response streaming
386 },
387 contextItems: [],
388 });
389 } else {
390 // New input/response messages
391 state.history = state.history.concat([
392 {
393 message: {
394 id: uuidv4(),
395 role: "user",
396 content: "", // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming
397 },
398 contextItems: [],
399 editorState,
400 },
401 {
402 message: {
403 id: uuidv4(),
404 role: "assistant",
405 content: "", // IMPORTANT - this is subsequently updated by response streaming
406 },
407 contextItems: [],
408 },
409 ]);
410 }
411
412 state.isStreaming = true;
413 },
414 truncateHistoryToMessage: (
415 state,
416 {
417 payload,
418 }: PayloadAction<{
419 index: number;
420 }>,
421 ) => {
422 const { index } = payload;
423
424 if (state.history.length && index < state.history.length) {
425 state.codeBlockApplyStates.curIndex = 0;
426 state.history = state.history.slice(0, index + 1).concat({
427 message: {
428 id: uuidv4(),
429 role: "assistant",
430 content: "", // IMPORTANT - this is subsequently updated by response streaming
431 },
432 contextItems: [],
433 });
434 state.inlineErrorMessage = undefined;
435 state.isPruned = false;
436 state.contextPercentage = undefined;
437 }
438 },
439 deleteMessage: (state, action: PayloadAction<number>) => {
440 // Deletes the current assistant message and the previous user message
441 state.history.splice(action.payload - 1, 2);
442 state.inlineErrorMessage = undefined;
443 state.isPruned = false;
444 state.contextPercentage = undefined;
445 },
446 deleteCompaction: (state, action: PayloadAction<number>) => {
447 // Removes the conversation summary from the specified message
448 const historyItem = state.history[action.payload];
449 if (historyItem?.conversationSummary) {
450 state.history[action.payload] = {
451 ...historyItem,
452 conversationSummary: undefined,
453 };
454 }
455 },
456 updateHistoryItemAtIndex: (
457 state,
458 {
459 payload,
460 }: PayloadAction<{
461 index: number;
462 updates: Partial<ChatHistoryItemWithMessageId>;
463 }>,
464 ) => {
465 const { index, updates } = payload;
466 if (index !== 0 && !state.history[index]) {
467 console.error(
468 `attempting to update history item at nonexistent index ${index}`,
469 updates,
470 );
471 return;
472 }
473 state.history[index] = {
474 ...state.history[index],
475 ...updates,
476 };
477 },
478 addContextItemsAtIndex: (
479 state,
480 {
481 payload,
482 }: PayloadAction<{
483 index: number;
484 contextItems: ContextItemWithId[];
485 }>,
486 ) => {
487 const historyItem = state.history[payload.index];
488
489 if (!historyItem) {
490 return;
491 }
492
493 historyItem.contextItems = [
494 ...historyItem.contextItems,
495 ...payload.contextItems,
496 ];
497 },
498 setAppliedRulesAtIndex: (
499 state,
500 {
501 payload,
502 }: PayloadAction<{
503 index: number;
504 appliedRules: RuleWithSource[];
505 }>,
506 ) => {
507 if (state.history[payload.index]) {
508 state.history[payload.index].appliedRules = payload.appliedRules;
509 }
510 },
511 setInactive: (state) => {
512 const curMessage = state.history.at(-1);
513
514 if (curMessage) {
515 curMessage.isGatheringContext = false;
516 }
517
518 state.isStreaming = false;
519 },
520 abortStream: (state) => {
521 state.streamAborter.abort();
522 state.streamAborter = new AbortController();
523 },
524 streamUpdate: (state, action: PayloadAction<ChatMessage[]>) => {
525 if (state.history.length) {
526 for (const message of action.payload) {
527 let lastItem = state.history[state.history.length - 1];
528 let lastMessage = lastItem.message;
529
530 if (message.role === "thinking" && message.redactedThinking) {
531 state.history.push({
532 message: {
533 role: "thinking",
534 content: "internal reasoning is hidden due to safety reasons",
535 redactedThinking: message.redactedThinking,
536 id: uuidv4(),
537 },
538 contextItems: [],
539 });
540 continue;
541 }
542
543 const messageContent = message.content
544 ? renderChatMessage(message)
545 : "";
546
547 // OpenAI-compatible models in agent mode sometimes send
548 // all of their data in one message, so we handle that case early.
549 if (messageContent && message.role !== "tool") {
550 const thinkMatches = messageContent.match(
551 /<think>([\s\S]*)<\/think>([\s\S]*)/,
552 );
553 if (thinkMatches) {
554 // The order that they seem to consistently use is:
555 //
556 // <think>Thinking text</think>
557 // Text to show to the user
558
559 lastItem.reasoning = {
560 text: thinkMatches[1].trim(),
561 startAt: Date.now(),
562 endAt: Date.now(),
563 active: false,
564 };
565
566 // This is the chat message that we should show to the user.
567 // We always need to push this even if it is empty,
568 // because we cannot attach tool calls to a Thinking message.
569 // That would break `messageHasToolCallId`.
570 state.history.push({
571 message: {
572 role: "assistant",
573 content: thinkMatches[2].trim(),
574 id: uuidv4(),
575 },
576 contextItems: [],
577 });
578 lastItem = state.history[state.history.length - 1];
579 lastMessage = lastItem.message;
580
581 handleToolCallsInMessage(message, lastItem);
582
583 return;
584 }
585 }
586
587 // The remainder of this function handles streaming messages
588 if (
589 lastMessage.role !== message.role ||
590 message.role === "tool" // Tool messages should always create new messages
591 ) {
592 // Create a new message
593 const historyItem: ChatHistoryItemWithMessageId = {
594 message: {
595 ...message,
596 content: "", // Start with empty content, let accumulation logic handle it
597 id: uuidv4(),
598 },
599 contextItems: [],
600 };
601 handleToolCallsInMessage(message, historyItem);
602 state.history.push(historyItem);
603 lastItem = state.history[state.history.length - 1];
604 lastMessage = lastItem.message;
605 }
606
607 // Add to the existing message
608 if (messageContent) {
609 if (messageContent.includes("<think>") && message.role !== "tool") {
610 lastItem.reasoning = {
611 startAt: Date.now(),
612 active: true,
613 text: messageContent.replace("<think>", "").trim(),
614 };
615 } else if (
616 lastItem.reasoning?.active &&
617 messageContent.includes("</think>")
618 ) {
619 const [reasoningEnd, answerStart] =
620 messageContent.split("</think>");
621 lastItem.reasoning.text += reasoningEnd.trimEnd();
622 lastItem.reasoning.active = false;
623 lastItem.reasoning.endAt = Date.now();
624 lastMessage.content += answerStart.trimStart();
625 } else if (lastItem.reasoning?.active) {
626 if (
627 lastItem.reasoning.text.length > 0 ||
628 messageContent.trim().length > 0
629 ) {
630 lastItem.reasoning.text += messageContent;
631 }
632 } else {
633 // Note this only works because new message above
634 // was already rendered from parts to string
635 if (
636 lastMessage.content.length > 0 ||
637 messageContent.trim().length > 0
638 ) {
639 lastMessage.content += messageContent;
640 }
641 }
642 } else if (message.role === "thinking" && message.signature) {
643 if (lastMessage.role === "thinking") {
644 lastMessage.signature = message.signature;
645 }
646 } else if (
647 message.role === "assistant" &&
648 message.toolCalls?.length &&
649 lastMessage.role === "assistant"
650 ) {
651 handleStreamingToolCallUpdates(message, lastItem);
652 }
653 }
654 }
655 },
656 newSession: (state, { payload }: PayloadAction<Session | undefined>) => {
657 state.lastSessionId = state.id;
658
659 state.streamAborter.abort();
660 state.streamAborter = new AbortController();
661
662 state.isStreaming = false;
663 state.symbols = {};
664
665 state.inlineErrorMessage = undefined;
666 state.isPruned = false;
667 state.contextPercentage = undefined;
668
669 if (payload) {
670 state.history = payload.history as any;
671 state.title = payload.title;
672 state.id = payload.sessionId;
673 } else {
674 state.history = [];
675 state.title = NEW_SESSION_TITLE;
676 state.id = uuidv4();
677 }
678 },
679 updateSessionTitle: (state, { payload }: PayloadAction<string>) => {
680 state.title = payload;
681 },
682 setIsSessionMetadataLoading: (
683 state,
684 { payload }: PayloadAction<boolean>,
685 ) => {
686 state.isSessionMetadataLoading = payload;
687 },
688 setAllSessionMetadata: (
689 state,
690 {
691 payload,
692 }: PayloadAction<(BaseSessionMetadata | RemoteSessionMetadata)[]>,
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<BaseSessionMetadata>,
701 ) => {
702 state.allSessionMetadata = [...state.allSessionMetadata, payload];
703 },
704 updateSessionMetadata: (
705 state,
706 {
707 payload,
708 }: PayloadAction<
709 {
710 sessionId: string;
711 } & Partial<BaseSessionMetadata>
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;