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