Elffuss BraidHub

kikocis/continue public

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