Elffuss BraidHub

kikocis/continue public

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