Elffuss BraidHub

kikocis/continue public

a0c996c3d18a · 21.9 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 ChatHistoryItem,
12 ChatMessage,
13 ContextItem,
14 ContextItemWithId,
15 FileSymbolMap,
16 MessageModes,
17 PromptLog,
18 RuleWithSource,
19 Session,
20 SessionMetadata,
21} from "core";
22import { NEW_SESSION_TITLE } from "core/util/constants";
23import {
24 renderChatMessage,
25 renderContextItems,
26} from "core/util/messageContent";
27import { findUriInDirs, getUriPathBasename } from "core/util/uri";
28import { findLastIndex } from "lodash";
29import { v4 as uuidv4 } from "uuid";
30import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem";
31import { addToolCallDeltaToState } from "../../util/toolCallState";
32import { RootState } from "../store";
33import { streamResponseThunk } from "../thunks/streamResponse";
34import { findCurrentToolCall, findToolCall, findToolOutput } from "../util";
35
36const getIdeMessenger = () => (window as any).ideMessenger;
37
38// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
39// The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
40export type ChatHistoryItemWithMessageId = ChatHistoryItem & {
41 message: ChatMessage & { id: string };
42};
43
44type SessionState = {
45 lastSessionId?: string;
46 allSessionMetadata: SessionMetadata[];
47 history: ChatHistoryItemWithMessageId[];
48 isStreaming: boolean;
49 title: string;
50 id: string;
51 streamAborter: AbortController;
52 mainEditorContentTrigger?: JSONContent | undefined;
53 symbols: FileSymbolMap;
54 mode: MessageModes;
55 isInEdit: boolean;
56 codeBlockApplyStates: {
57 states: ApplyState[];
58 curIndex: number;
59 };
60 newestToolbarPreviewForInput: Record<string, string>;
61 hasReasoningEnabled?: boolean;
62};
63
64const initialState: SessionState = {
65 allSessionMetadata: [],
66 history: [],
67 isStreaming: false,
68 title: NEW_SESSION_TITLE,
69 id: uuidv4(),
70 streamAborter: new AbortController(),
71 symbols: {},
72 mode: "chat",
73 isInEdit: false,
74 codeBlockApplyStates: {
75 states: [],
76 curIndex: 0,
77 },
78 lastSessionId: undefined,
79 newestToolbarPreviewForInput: {},
80};
81
82export const sessionSlice = createSlice({
83 name: "session",
84 initialState,
85 reducers: {
86 addPromptCompletionPair: (
87 state,
88 { payload }: PayloadAction<PromptLog[]>,
89 ) => {
90 if (!state.history.length) {
91 return;
92 }
93
94 const lastMessage = state.history[state.history.length - 1];
95
96 lastMessage.promptLogs = lastMessage.promptLogs
97 ? lastMessage.promptLogs.concat(payload)
98 : payload;
99
100 // Inactive thinking for reasoning models when '</think>' tag is not received on request completion
101 if (lastMessage.reasoning?.active) {
102 lastMessage.reasoning.active = false;
103 lastMessage.reasoning.endAt = Date.now();
104 }
105 },
106 setActive: (state) => {
107 state.isStreaming = true;
108 },
109 setIsGatheringContext: (state, { payload }: PayloadAction<boolean>) => {
110 const curMessage = state.history.at(-1);
111 if (curMessage) {
112 curMessage.isGatheringContext = payload;
113 }
114 },
115 clearDanglingMessages: (state) => {
116 // This is used during cancellation
117 // After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing.
118 // The only thing allowed after the last assistant message that has either content or generated tool calls
119 // is a user or tool message
120 if (state.history.length < 2) {
121 return;
122 }
123 const lastUserOrToolIdx = findLastIndex(
124 state.history,
125 (item) => item.message.role === "tool" || item.message.role === "user",
126 );
127
128 let validAssistantMessageIdx = -1;
129 for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) {
130 const message = state.history[i];
131 if (
132 message.message.content ||
133 message.toolCallState?.status !== "generating"
134 ) {
135 validAssistantMessageIdx = i;
136 // Cancel any tool calls that are dangling and generated
137 if (message.toolCallState?.status === "generated") {
138 message.toolCallState.status = "canceled";
139 }
140 break;
141 }
142 }
143
144 if (validAssistantMessageIdx === -1) {
145 state.history = state.history.slice(0, lastUserOrToolIdx + 1);
146 } else {
147 state.history = state.history.slice(0, validAssistantMessageIdx + 1);
148 }
149 },
150 // Trigger value picked up by editor with isMainInput to set its content
151 setMainEditorContentTrigger: (
152 state,
153 action: PayloadAction<JSONContent | undefined>,
154 ) => {
155 state.mainEditorContentTrigger = action.payload;
156 },
157 updateFileSymbols: (state, action: PayloadAction<FileSymbolMap>) => {
158 state.symbols = {
159 ...state.symbols,
160 ...action.payload,
161 };
162 },
163 setContextItemsAtIndex: (
164 state,
165 {
166 payload: { index, contextItems },
167 }: PayloadAction<{
168 index: number;
169 contextItems: ChatHistoryItem["contextItems"];
170 }>,
171 ) => {
172 if (state.history[index]) {
173 state.history[index].contextItems = contextItems;
174 }
175 },
176 submitEditorAndInitAtIndex: (
177 state,
178 {
179 payload,
180 }: PayloadAction<{
181 index: number;
182 editorState: JSONContent;
183 }>,
184 ) => {
185 const { index, editorState } = payload;
186
187 if (state.history.length && index < state.history.length) {
188 // Resubmission - update input message, truncate history after resubmit with new empty response message
189 if (index % 2 === 1) {
190 console.warn(
191 "Corrupted history: resubmitting at odd index, shouldn't happen",
192 );
193 }
194 const historyItem = state.history[index];
195
196 historyItem.message.content = ""; // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming
197 historyItem.editorState = payload.editorState;
198 historyItem.contextItems = [];
199
200 state.history = state.history.slice(0, index + 1).concat({
201 message: {
202 id: uuidv4(),
203 role: "assistant",
204 content: "", // IMPORTANT - this is subsequently updated by response streaming
205 },
206 contextItems: [],
207 });
208 } else {
209 // New input/response messages
210 state.history = state.history.concat([
211 {
212 message: {
213 id: uuidv4(),
214 role: "user",
215 content: "", // IMPORTANT - this is quickly updated by resolveEditorContent based on editor state prior to streaming
216 },
217 contextItems: [],
218 editorState,
219 },
220 {
221 message: {
222 id: uuidv4(),
223 role: "assistant",
224 content: "", // IMPORTANT - this is subsequently updated by response streaming
225 },
226 contextItems: [],
227 },
228 ]);
229 }
230
231 state.isStreaming = true;
232 },
233 deleteMessage: (state, action: PayloadAction<number>) => {
234 // Deletes the current assistant message and the previous user message
235 state.history.splice(action.payload - 1, 2);
236 },
237 updateHistoryItemAtIndex: (
238 state,
239 {
240 payload,
241 }: PayloadAction<{
242 index: number;
243 updates: Partial<ChatHistoryItemWithMessageId>;
244 }>,
245 ) => {
246 const { index, updates } = payload;
247 if (index !== 0 && !state.history[index]) {
248 console.error(
249 `attempting to update history item at nonexistent index ${index}`,
250 updates,
251 );
252 return;
253 }
254 state.history[index] = {
255 ...state.history[index],
256 ...updates,
257 };
258 },
259 addContextItemsAtIndex: (
260 state,
261 {
262 payload,
263 }: PayloadAction<{
264 index: number;
265 contextItems: ContextItemWithId[];
266 }>,
267 ) => {
268 const historyItem = state.history[payload.index];
269
270 if (!historyItem) {
271 return;
272 }
273
274 historyItem.contextItems = [
275 ...historyItem.contextItems,
276 ...payload.contextItems,
277 ];
278 },
279 setAppliedRulesAtIndex: (
280 state,
281 {
282 payload,
283 }: PayloadAction<{
284 index: number;
285 appliedRules: RuleWithSource[];
286 }>,
287 ) => {
288 if (state.history[payload.index]) {
289 state.history[payload.index].appliedRules = payload.appliedRules;
290 }
291 },
292 setInactive: (state) => {
293 const curMessage = state.history.at(-1);
294
295 if (curMessage) {
296 curMessage.isGatheringContext = false;
297 }
298
299 state.isStreaming = false;
300 },
301 abortStream: (state) => {
302 state.streamAborter.abort();
303 state.streamAborter = new AbortController();
304 },
305 streamUpdate: (state, action: PayloadAction<ChatMessage[]>) => {
306 if (state.history.length) {
307 for (const message of action.payload) {
308 const lastItem = state.history[state.history.length - 1];
309 const lastMessage = lastItem.message;
310
311 if (message.role === "thinking" && message.redactedThinking) {
312 console.log("add redacted_thinking blocks");
313
314 state.history.push({
315 message: {
316 role: "thinking",
317 content: "internal reasoning is hidden due to safety reasons",
318 redactedThinking: message.redactedThinking,
319 id: uuidv4(),
320 },
321 contextItems: [],
322 });
323 continue;
324 }
325
326 if (
327 lastMessage.role !== message.role ||
328 // This is for when a tool call comes immediately before/after tool call
329 (lastMessage.role === "assistant" &&
330 message.role === "assistant" &&
331 // Last message isn't completely new
332 !(!lastMessage.toolCalls?.length && !lastMessage.content) &&
333 // And there's a difference in tool call presence
334 (lastMessage.toolCalls?.length ?? 0) !==
335 (message.toolCalls?.length ?? 0))
336 ) {
337 // Create a new message
338 const historyItem: ChatHistoryItemWithMessageId = {
339 message: {
340 ...message,
341 content: renderChatMessage(message),
342 id: uuidv4(),
343 },
344 contextItems: [],
345 };
346 if (message.role === "assistant" && message.toolCalls?.[0]) {
347 const toolCallDelta = message.toolCalls[0];
348 historyItem.toolCallState = addToolCallDeltaToState(
349 toolCallDelta,
350 undefined,
351 );
352 }
353 state.history.push(historyItem);
354 } else {
355 // Add to the existing message
356 if (message.content) {
357 const messageContent = renderChatMessage(message);
358 if (messageContent.includes("<think>")) {
359 lastItem.reasoning = {
360 startAt: Date.now(),
361 active: true,
362 text: messageContent.replace("<think>", "").trim(),
363 };
364 } else if (
365 lastItem.reasoning?.active &&
366 messageContent.includes("</think>")
367 ) {
368 const [reasoningEnd, answerStart] =
369 messageContent.split("</think>");
370 lastItem.reasoning.text += reasoningEnd.trimEnd();
371 lastItem.reasoning.active = false;
372 lastItem.reasoning.endAt = Date.now();
373 lastMessage.content += answerStart.trimStart();
374 } else if (lastItem.reasoning?.active) {
375 lastItem.reasoning.text += messageContent;
376 } else {
377 // Note this only works because new message above
378 // was already rendered from parts to string
379 lastMessage.content += messageContent;
380 }
381 } else if (message.role === "thinking" && message.signature) {
382 if (lastMessage.role === "thinking") {
383 console.log("add signature", message.signature);
384 lastMessage.signature = message.signature;
385 }
386 } else if (
387 message.role === "assistant" &&
388 message.toolCalls?.[0] &&
389 lastMessage.role === "assistant"
390 ) {
391 // Intentionally only supporting one tool call for now.
392 const toolCallDelta = message.toolCalls[0];
393 const newToolCallState = addToolCallDeltaToState(
394 toolCallDelta,
395 lastItem.toolCallState,
396 );
397 lastItem.toolCallState = newToolCallState;
398 lastMessage.toolCalls = [newToolCallState.toolCall];
399 }
400 }
401 }
402 }
403 },
404 newSession: (state, { payload }: PayloadAction<Session | undefined>) => {
405 state.lastSessionId = state.id;
406
407 state.streamAborter.abort();
408 state.streamAborter = new AbortController();
409
410 state.isStreaming = false;
411 state.symbols = {};
412
413 if (payload) {
414 state.history = payload.history as any;
415 state.title = payload.title;
416 state.id = payload.sessionId;
417 } else {
418 state.history = [];
419 state.title = NEW_SESSION_TITLE;
420 state.id = uuidv4();
421 }
422 },
423 updateSessionTitle: (state, { payload }: PayloadAction<string>) => {
424 state.title = payload;
425 },
426 setAllSessionMetadata: (
427 state,
428 { payload }: PayloadAction<SessionMetadata[]>,
429 ) => {
430 state.allSessionMetadata = payload;
431 },
432 //////////////////////////////////////////////////////////////////////////////////
433 // These are for optimistic session metadata updates, especially for History page
434 addSessionMetadata: (
435 state,
436 { payload }: PayloadAction<SessionMetadata>,
437 ) => {
438 state.allSessionMetadata = [...state.allSessionMetadata, payload];
439 },
440 updateSessionMetadata: (
441 state,
442 {
443 payload,
444 }: PayloadAction<
445 {
446 sessionId: string;
447 } & Partial<SessionMetadata>
448 >,
449 ) => {
450 state.allSessionMetadata = state.allSessionMetadata.map((session) =>
451 session.sessionId === payload.sessionId
452 ? {
453 ...session,
454 ...payload,
455 }
456 : session,
457 );
458 if (payload.title && payload.sessionId === state.id) {
459 state.title = payload.title;
460 }
461 },
462 deleteSessionMetadata: (state, { payload }: PayloadAction<string>) => {
463 // Note, should not be allowed to delete current session from chat session
464 state.allSessionMetadata = state.allSessionMetadata.filter(
465 (session) => session.sessionId !== payload,
466 );
467 },
468 //////////////////////////////////////////////////////////////////////////////////
469 addHighlightedCode: (
470 state,
471 {
472 payload,
473 }: PayloadAction<{ rangeInFileWithContents: any; edit: boolean }>,
474 ) => {
475 let contextItems =
476 state.history[state.history.length - 1].contextItems ?? [];
477
478 contextItems = contextItems.map((item) => {
479 return { ...item, editing: false };
480 });
481
482 const { relativePathOrBasename } = findUriInDirs(
483 payload.rangeInFileWithContents.filepath,
484 window.workspacePaths ?? [],
485 );
486 const fileName = getUriPathBasename(
487 payload.rangeInFileWithContents.filepath,
488 );
489
490 const lineNums = `(${
491 payload.rangeInFileWithContents.range.start.line + 1
492 }-${payload.rangeInFileWithContents.range.end.line + 1})`;
493
494 contextItems.push({
495 name: `${fileName} ${lineNums}`,
496 description: relativePathOrBasename,
497 id: {
498 providerTitle: "code",
499 itemId: uuidv4(),
500 },
501 content: payload.rangeInFileWithContents.contents,
502 editing: true,
503 editable: true,
504 uri: {
505 type: "file",
506 value: payload.rangeInFileWithContents.filepath,
507 },
508 });
509
510 state.history[state.history.length - 1].contextItems = contextItems;
511 },
512 updateApplyState: (state, { payload }: PayloadAction<ApplyState>) => {
513 const applyState = state.codeBlockApplyStates.states.find(
514 (state) => state.streamId === payload.streamId,
515 );
516
517 if (!applyState) {
518 state.codeBlockApplyStates.states.push(payload);
519 } else {
520 applyState.status = payload.status ?? applyState.status;
521 applyState.numDiffs = payload.numDiffs ?? applyState.numDiffs;
522 applyState.filepath = payload.filepath ?? applyState.filepath;
523 }
524
525 if (payload.status === "done") {
526 state.codeBlockApplyStates.curIndex++;
527 }
528 },
529 resetNextCodeBlockToApplyIndex: (state) => {
530 state.codeBlockApplyStates.curIndex = 0;
531 },
532
533 // TOOL CALL STATE
534 setToolGenerated: (
535 state,
536 action: PayloadAction<{
537 toolCallId: string;
538 }>,
539 ) => {
540 const toolCallState = findToolCall(
541 state.history,
542 action.payload.toolCallId,
543 );
544 if (toolCallState) {
545 toolCallState.status = "generated";
546 }
547 },
548 updateToolCallOutput: (
549 state,
550 action: PayloadAction<{
551 toolCallId: string;
552 contextItems: ContextItem[];
553 }>,
554 ) => {
555 // Update tool call state and corresponding tool output message
556 const toolCallState = findToolCall(
557 state.history,
558 action.payload.toolCallId,
559 );
560 if (toolCallState) {
561 toolCallState.output = action.payload.contextItems;
562 }
563 const toolItem = findToolOutput(state.history, action.payload.toolCallId);
564 if (toolItem) {
565 toolItem.message.content = renderContextItems(
566 action.payload.contextItems,
567 );
568 toolItem.contextItems = action.payload.contextItems.map((item) =>
569 toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId),
570 );
571 }
572 },
573 cancelToolCall: (
574 state,
575 action: PayloadAction<{
576 toolCallId: string;
577 }>,
578 ) => {
579 const toolCallState = findToolCall(
580 state.history,
581 action.payload.toolCallId,
582 );
583 if (toolCallState) {
584 toolCallState.status = "canceled";
585 }
586 },
587 errorToolCall: (
588 state,
589 action: PayloadAction<{
590 toolCallId: string;
591 }>,
592 ) => {
593 const toolCallState = findToolCall(
594 state.history,
595 action.payload.toolCallId,
596 );
597 if (toolCallState) {
598 toolCallState.status = "errored";
599 }
600 },
601 acceptToolCall: (
602 state,
603 action: PayloadAction<{
604 toolCallId: string;
605 }>,
606 ) => {
607 const toolCallState = findToolCall(
608 state.history,
609 action.payload.toolCallId,
610 );
611 if (toolCallState) {
612 toolCallState.status = "done";
613 }
614 },
615 setToolCallCalling: (
616 state,
617 action: PayloadAction<{
618 toolCallId: string;
619 }>,
620 ) => {
621 const toolCallState = findToolCall(
622 state.history,
623 action.payload.toolCallId,
624 );
625 if (toolCallState) {
626 toolCallState.status = "calling";
627 }
628 },
629 setMode: (state, action: PayloadAction<MessageModes>) => {
630 state.mode = action.payload;
631 },
632 setIsInEdit: (state, action: PayloadAction<boolean>) => {
633 state.isInEdit = action.payload;
634 },
635 setHasReasoningEnabled: (state, action: PayloadAction<boolean>) => {
636 state.hasReasoningEnabled = action.payload;
637 },
638 setNewestToolbarPreviewForInput: (
639 state,
640 {
641 payload,
642 }: PayloadAction<{
643 inputId: string;
644 contextItemId: string;
645 }>,
646 ) => {
647 state.newestToolbarPreviewForInput[payload.inputId] =
648 payload.contextItemId;
649 },
650 },
651 selectors: {
652 selectIsGatheringContext: (state) => {
653 const curHistoryItem = state.history.at(-1);
654 return curHistoryItem?.isGatheringContext || false;
655 },
656 },
657 extraReducers: (builder) => {
658 addPassthroughCases(builder, [streamResponseThunk]);
659 },
660});
661
662function addPassthroughCases(
663 builder: ActionReducerMapBuilder<SessionState>,
664 thunks: AsyncThunk<any, any, any>[],
665) {
666 thunks.forEach((thunk) => {
667 builder
668 .addCase(thunk.fulfilled, (state, action) => {})
669 .addCase(thunk.rejected, (state, action) => {})
670 .addCase(thunk.pending, (state, action) => {});
671 });
672}
673
674export const selectCurrentToolCall = createSelector(
675 (store: RootState) => store.session.history,
676 (history) => {
677 return findCurrentToolCall(history);
678 },
679);
680
681export const selectApplyStateByStreamId = createSelector(
682 [
683 (state: RootState) => state.session.codeBlockApplyStates.states,
684 (state: RootState, streamId?: string) => streamId,
685 ],
686 (states, streamId) => {
687 return states.find((state) => state.streamId === streamId);
688 },
689);
690
691export const selectApplyStateByToolCallId = createSelector(
692 [
693 (state: RootState) => state.session.codeBlockApplyStates.states,
694 (state: RootState, toolCallId?: string) => toolCallId,
695 ],
696 (states, toolCallId) => {
697 if (toolCallId) {
698 return states.find((state) => state.toolCallId === toolCallId);
699 }
700 },
701);
702
703export const {
704 updateFileSymbols,
705 setContextItemsAtIndex,
706 addContextItemsAtIndex,
707 setAppliedRulesAtIndex,
708 setInactive,
709 streamUpdate,
710 newSession,
711 updateSessionTitle,
712 addHighlightedCode,
713 addPromptCompletionPair,
714 setActive,
715 submitEditorAndInitAtIndex,
716 updateHistoryItemAtIndex,
717 clearDanglingMessages,
718 setMainEditorContentTrigger,
719 deleteMessage,
720 setIsGatheringContext,
721 resetNextCodeBlockToApplyIndex,
722 updateApplyState,
723 abortStream,
724 setToolCallCalling,
725 cancelToolCall,
726 errorToolCall,
727 acceptToolCall,
728 setToolGenerated,
729 updateToolCallOutput,
730 setMode,
731 setAllSessionMetadata,
732 addSessionMetadata,
733 updateSessionMetadata,
734 deleteSessionMetadata,
735 setNewestToolbarPreviewForInput,
736 setIsInEdit,
737 setHasReasoningEnabled,
738} = sessionSlice.actions;
739
740export const { selectIsGatheringContext } = sessionSlice.selectors;
741
742export default sessionSlice.reducer;