| 1 | import { |
| 2 | ArrowLeftIcon, |
| 3 | ChatBubbleOvalLeftIcon, |
| 4 | } from "@heroicons/react/24/outline"; |
| 5 | import { Editor, JSONContent } from "@tiptap/react"; |
| 6 | import { ChatHistoryItem, InputModifiers } from "core"; |
| 7 | import { renderChatMessage } from "core/util/messageContent"; |
| 8 | import { |
| 9 | useCallback, |
| 10 | useContext, |
| 11 | useEffect, |
| 12 | useMemo, |
| 13 | useRef, |
| 14 | useState, |
| 15 | } from "react"; |
| 16 | import { ErrorBoundary } from "react-error-boundary"; |
| 17 | import styled from "styled-components"; |
| 18 | import { Button, lightGray, vscBackground } from "../../components"; |
| 19 | import { useFindWidget } from "../../components/find/FindWidget"; |
| 20 | import TimelineItem from "../../components/gui/TimelineItem"; |
| 21 | import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton"; |
| 22 | import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek"; |
| 23 | import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; |
| 24 | import { useOnboardingCard } from "../../components/OnboardingCard"; |
| 25 | import StepContainer from "../../components/StepContainer"; |
| 26 | import { TabBar } from "../../components/TabBar/TabBar"; |
| 27 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 28 | import { useWebviewListener } from "../../hooks/useWebviewListener"; |
| 29 | import { useAppDispatch, useAppSelector } from "../../redux/hooks"; |
| 30 | import { |
| 31 | selectDoneApplyStates, |
| 32 | selectPendingToolCalls, |
| 33 | } from "../../redux/selectors/selectToolCalls"; |
| 34 | import { |
| 35 | cancelToolCall, |
| 36 | ChatHistoryItemWithMessageId, |
| 37 | newSession, |
| 38 | updateToolCallOutput, |
| 39 | } from "../../redux/slices/sessionSlice"; |
| 40 | import { streamEditThunk } from "../../redux/thunks/edit"; |
| 41 | import { loadLastSession } from "../../redux/thunks/session"; |
| 42 | import { streamResponseThunk } from "../../redux/thunks/streamResponse"; |
| 43 | import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; |
| 44 | import { ToolCallDiv } from "./ToolCallDiv"; |
| 45 | |
| 46 | import { FatalErrorIndicator } from "../../components/config/FatalErrorNotice"; |
| 47 | import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; |
| 48 | import { cancelStream } from "../../redux/thunks/cancelStream"; |
| 49 | import { EmptyChatBody } from "./EmptyChatBody"; |
| 50 | import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; |
| 51 | import { useAutoScroll } from "./useAutoScroll"; |
| 52 | |
| 53 | // Helper function to find the index of the latest conversation summary |
| 54 | function findLatestSummaryIndex(history: ChatHistoryItem[]): number { |
| 55 | for (let i = history.length - 1; i >= 0; i--) { |
| 56 | if (history[i].conversationSummary) { |
| 57 | return i; |
| 58 | } |
| 59 | } |
| 60 | return -1; // No summary found |
| 61 | } |
| 62 | |
| 63 | const StepsDiv = styled.div` |
| 64 | position: relative; |
| 65 | background-color: transparent; |
| 66 | |
| 67 | & > * { |
| 68 | position: relative; |
| 69 | } |
| 70 | |
| 71 | .thread-message { |
| 72 | margin: 0 0 0 1px; |
| 73 | } |
| 74 | `; |
| 75 | |
| 76 | export const MAIN_EDITOR_INPUT_ID = "main-editor-input"; |
| 77 | |
| 78 | function fallbackRender({ error, resetErrorBoundary }: any) { |
| 79 | // Call resetErrorBoundary() to reset the error boundary and retry the render. |
| 80 | |
| 81 | return ( |
| 82 | <div |
| 83 | role="alert" |
| 84 | className="px-2" |
| 85 | style={{ backgroundColor: vscBackground }} |
| 86 | > |
| 87 | <p>Something went wrong:</p> |
| 88 | <pre style={{ color: "red" }}>{error.message}</pre> |
| 89 | <pre style={{ color: lightGray }}>{error.stack}</pre> |
| 90 | |
| 91 | <div className="text-center"> |
| 92 | <Button onClick={resetErrorBoundary}>Restart</Button> |
| 93 | </div> |
| 94 | </div> |
| 95 | ); |
| 96 | } |
| 97 | |
| 98 | export function Chat() { |
| 99 | const dispatch = useAppDispatch(); |
| 100 | const ideMessenger = useContext(IdeMessengerContext); |
| 101 | const onboardingCard = useOnboardingCard(); |
| 102 | const showSessionTabs = useAppSelector( |
| 103 | (store) => store.config.config.ui?.showSessionTabs, |
| 104 | ); |
| 105 | const selectedModels = useAppSelector( |
| 106 | (store) => store.config?.config.selectedModelByRole, |
| 107 | ); |
| 108 | const isStreaming = useAppSelector((state) => state.session.isStreaming); |
| 109 | const [stepsOpen] = useState<(boolean | undefined)[]>([]); |
| 110 | const mainTextInputRef = useRef<HTMLInputElement>(null); |
| 111 | const stepsDivRef = useRef<HTMLDivElement>(null); |
| 112 | const tabsRef = useRef<HTMLDivElement>(null); |
| 113 | const history = useAppSelector((state) => state.session.history); |
| 114 | const showChatScrollbar = useAppSelector( |
| 115 | (state) => state.config.config.ui?.showChatScrollbar, |
| 116 | ); |
| 117 | const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit); |
| 118 | const mode = useAppSelector((store) => store.session.mode); |
| 119 | const isInEdit = useAppSelector((store) => store.session.isInEdit); |
| 120 | |
| 121 | const lastSessionId = useAppSelector((state) => state.session.lastSessionId); |
| 122 | const hasDismissedExploreDialog = useAppSelector( |
| 123 | (state) => state.ui.hasDismissedExploreDialog, |
| 124 | ); |
| 125 | const jetbrains = useMemo(() => { |
| 126 | return isJetBrains(); |
| 127 | }, []); |
| 128 | |
| 129 | useAutoScroll(stepsDivRef, history); |
| 130 | |
| 131 | useEffect(() => { |
| 132 | // Cmd + Backspace to delete current step |
| 133 | const listener = (e: KeyboardEvent) => { |
| 134 | if ( |
| 135 | e.key === "Backspace" && |
| 136 | (jetbrains ? e.altKey : isMetaEquivalentKeyPressed(e)) && |
| 137 | !e.shiftKey |
| 138 | ) { |
| 139 | void dispatch(cancelStream()); |
| 140 | } |
| 141 | }; |
| 142 | window.addEventListener("keydown", listener); |
| 143 | |
| 144 | return () => { |
| 145 | window.removeEventListener("keydown", listener); |
| 146 | }; |
| 147 | }, [isStreaming, jetbrains, isInEdit]); |
| 148 | |
| 149 | const { widget, highlights } = useFindWidget( |
| 150 | stepsDivRef, |
| 151 | tabsRef, |
| 152 | isStreaming, |
| 153 | ); |
| 154 | |
| 155 | const pendingToolCalls = useAppSelector(selectPendingToolCalls); |
| 156 | const pendingApplyStates = useAppSelector(selectDoneApplyStates); |
| 157 | |
| 158 | const sendInput = useCallback( |
| 159 | ( |
| 160 | editorState: JSONContent, |
| 161 | modifiers: InputModifiers, |
| 162 | index?: number, |
| 163 | editorToClearOnSend?: Editor, |
| 164 | ) => { |
| 165 | // Cancel all pending tool calls |
| 166 | pendingToolCalls.forEach((toolCallState) => { |
| 167 | dispatch( |
| 168 | cancelToolCall({ |
| 169 | toolCallId: toolCallState.toolCallId, |
| 170 | }), |
| 171 | ); |
| 172 | }); |
| 173 | |
| 174 | // Reject all pending apply states |
| 175 | pendingApplyStates.forEach((applyState) => { |
| 176 | if (applyState.status !== "closed") { |
| 177 | ideMessenger.post("rejectDiff", applyState); |
| 178 | } |
| 179 | }); |
| 180 | const model = isInEdit |
| 181 | ? (selectedModels?.edit ?? selectedModels?.chat) |
| 182 | : selectedModels?.chat; |
| 183 | if (!model) { |
| 184 | return; |
| 185 | } |
| 186 | |
| 187 | if (isInEdit && codeToEdit.length === 0) { |
| 188 | return; |
| 189 | } |
| 190 | |
| 191 | // TODO - hook up with hub to detect free trial progress |
| 192 | // if (model.provider === "free-trial") { |
| 193 | // const newCount = incrementFreeTrialCount(); |
| 194 | |
| 195 | // if (newCount === FREE_TRIAL_LIMIT_REQUESTS) { |
| 196 | // posthog?.capture("ftc_reached"); |
| 197 | // } |
| 198 | // if (newCount >= FREE_TRIAL_LIMIT_REQUESTS) { |
| 199 | // // Show this message whether using platform or not |
| 200 | // // So that something happens if in new chat |
| 201 | // void ideMessenger.ide.showToast( |
| 202 | // "error", |
| 203 | // "You've reached the free trial limit. Please configure a model to continue.", |
| 204 | // ); |
| 205 | |
| 206 | // // If history, show the dialog, which will automatically close if there is not history |
| 207 | // if (history.length) { |
| 208 | // dispatch(setDialogMessage(<FreeTrialOverDialog />)); |
| 209 | // dispatch(setShowDialog(true)); |
| 210 | // } |
| 211 | // return; |
| 212 | // } |
| 213 | // } |
| 214 | |
| 215 | if (isInEdit) { |
| 216 | void dispatch( |
| 217 | streamEditThunk({ |
| 218 | editorState, |
| 219 | codeToEdit, |
| 220 | }), |
| 221 | ); |
| 222 | } else { |
| 223 | void dispatch(streamResponseThunk({ editorState, modifiers, index })); |
| 224 | |
| 225 | if (editorToClearOnSend) { |
| 226 | editorToClearOnSend.commands.clearContent(); |
| 227 | } |
| 228 | } |
| 229 | }, |
| 230 | [ |
| 231 | history, |
| 232 | selectedModels, |
| 233 | mode, |
| 234 | isInEdit, |
| 235 | codeToEdit, |
| 236 | pendingToolCalls, |
| 237 | pendingApplyStates, |
| 238 | ], |
| 239 | ); |
| 240 | |
| 241 | useWebviewListener( |
| 242 | "newSession", |
| 243 | async () => { |
| 244 | // unwrapResult(response) // errors if session creation failed |
| 245 | mainTextInputRef.current?.focus?.(); |
| 246 | }, |
| 247 | [mainTextInputRef], |
| 248 | ); |
| 249 | |
| 250 | // Handle partial tool call output for streaming updates |
| 251 | useWebviewListener( |
| 252 | "toolCallPartialOutput", |
| 253 | async (data) => { |
| 254 | // Update tool call output in Redux store |
| 255 | dispatch( |
| 256 | updateToolCallOutput({ |
| 257 | toolCallId: data.toolCallId, |
| 258 | contextItems: data.contextItems, |
| 259 | }), |
| 260 | ); |
| 261 | }, |
| 262 | [dispatch], |
| 263 | ); |
| 264 | |
| 265 | const isLastUserInput = useCallback( |
| 266 | (index: number): boolean => { |
| 267 | return !history |
| 268 | .slice(index + 1) |
| 269 | .some((entry) => entry.message.role === "user"); |
| 270 | }, |
| 271 | [history], |
| 272 | ); |
| 273 | |
| 274 | const renderChatHistoryItem = useCallback( |
| 275 | (item: ChatHistoryItemWithMessageId, index: number) => { |
| 276 | const { |
| 277 | message, |
| 278 | editorState, |
| 279 | contextItems, |
| 280 | appliedRules, |
| 281 | toolCallStates, |
| 282 | } = item; |
| 283 | |
| 284 | // Calculate once for the entire function |
| 285 | const latestSummaryIndex = findLatestSummaryIndex(history); |
| 286 | const isBeforeLatestSummary = |
| 287 | latestSummaryIndex !== -1 && index < latestSummaryIndex; |
| 288 | |
| 289 | if (message.role === "user") { |
| 290 | return ( |
| 291 | <div className={isBeforeLatestSummary ? "opacity-50" : ""}> |
| 292 | <ContinueInputBox |
| 293 | onEnter={(editorState, modifiers) => |
| 294 | sendInput(editorState, modifiers, index) |
| 295 | } |
| 296 | isLastUserInput={isLastUserInput(index)} |
| 297 | isMainInput={false} |
| 298 | editorState={editorState} |
| 299 | contextItems={contextItems} |
| 300 | appliedRules={appliedRules} |
| 301 | inputId={message.id} |
| 302 | /> |
| 303 | </div> |
| 304 | ); |
| 305 | } |
| 306 | |
| 307 | if (message.role === "tool") { |
| 308 | return null; |
| 309 | } |
| 310 | |
| 311 | if (message.role === "assistant") { |
| 312 | return ( |
| 313 | <> |
| 314 | {/* Always render assistant content through normal path */} |
| 315 | <div className="thread-message"> |
| 316 | <TimelineItem |
| 317 | item={item} |
| 318 | iconElement={ |
| 319 | <ChatBubbleOvalLeftIcon width="16px" height="16px" /> |
| 320 | } |
| 321 | open={ |
| 322 | typeof stepsOpen[index] === "undefined" |
| 323 | ? true |
| 324 | : stepsOpen[index]! |
| 325 | } |
| 326 | onToggle={() => {}} |
| 327 | > |
| 328 | <StepContainer |
| 329 | index={index} |
| 330 | isLast={index === history.length - 1} |
| 331 | item={item} |
| 332 | latestSummaryIndex={latestSummaryIndex} |
| 333 | /> |
| 334 | </TimelineItem> |
| 335 | </div> |
| 336 | |
| 337 | {toolCallStates && ( |
| 338 | <ToolCallDiv |
| 339 | toolCallStates={toolCallStates} |
| 340 | historyIndex={index} |
| 341 | /> |
| 342 | )} |
| 343 | </> |
| 344 | ); |
| 345 | } |
| 346 | |
| 347 | if (message.role === "thinking") { |
| 348 | return ( |
| 349 | <div className={isBeforeLatestSummary ? "opacity-50" : ""}> |
| 350 | <ThinkingBlockPeek |
| 351 | content={renderChatMessage(message)} |
| 352 | redactedThinking={message.redactedThinking} |
| 353 | index={index} |
| 354 | prevItem={index > 0 ? history[index - 1] : null} |
| 355 | inProgress={index === history.length - 1} |
| 356 | signature={message.signature} |
| 357 | /> |
| 358 | </div> |
| 359 | ); |
| 360 | } |
| 361 | |
| 362 | // Default case - regular assistant message |
| 363 | return ( |
| 364 | <div className="thread-message"> |
| 365 | <TimelineItem |
| 366 | item={item} |
| 367 | iconElement={<ChatBubbleOvalLeftIcon width="16px" height="16px" />} |
| 368 | open={ |
| 369 | typeof stepsOpen[index] === "undefined" ? true : stepsOpen[index]! |
| 370 | } |
| 371 | onToggle={() => {}} |
| 372 | > |
| 373 | <StepContainer |
| 374 | index={index} |
| 375 | isLast={index === history.length - 1} |
| 376 | item={item} |
| 377 | latestSummaryIndex={latestSummaryIndex} |
| 378 | /> |
| 379 | </TimelineItem> |
| 380 | </div> |
| 381 | ); |
| 382 | }, |
| 383 | [sendInput, isLastUserInput, history, stepsOpen], |
| 384 | ); |
| 385 | |
| 386 | const showScrollbar = showChatScrollbar ?? window.innerHeight > 5000; |
| 387 | |
| 388 | return ( |
| 389 | <> |
| 390 | {!!showSessionTabs && !isInEdit && <TabBar ref={tabsRef} />} |
| 391 | {widget} |
| 392 | |
| 393 | <StepsDiv |
| 394 | ref={stepsDivRef} |
| 395 | className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`} |
| 396 | > |
| 397 | {highlights} |
| 398 | {history.map((item, index: number) => ( |
| 399 | <div |
| 400 | key={item.message.id} |
| 401 | style={{ |
| 402 | minHeight: index === history.length - 1 ? "200px" : 0, |
| 403 | }} |
| 404 | > |
| 405 | <ErrorBoundary |
| 406 | FallbackComponent={fallbackRender} |
| 407 | onReset={() => { |
| 408 | dispatch(newSession()); |
| 409 | }} |
| 410 | > |
| 411 | {renderChatHistoryItem(item, index)} |
| 412 | </ErrorBoundary> |
| 413 | {index === history.length - 1 && <InlineErrorMessage />} |
| 414 | </div> |
| 415 | ))} |
| 416 | </StepsDiv> |
| 417 | <div className={"relative"}> |
| 418 | <ContinueInputBox |
| 419 | isMainInput |
| 420 | isLastUserInput={false} |
| 421 | onEnter={(editorState, modifiers, editor) => |
| 422 | sendInput(editorState, modifiers, undefined, editor) |
| 423 | } |
| 424 | inputId={MAIN_EDITOR_INPUT_ID} |
| 425 | /> |
| 426 | |
| 427 | <div |
| 428 | style={{ |
| 429 | pointerEvents: isStreaming ? "none" : "auto", |
| 430 | }} |
| 431 | > |
| 432 | <div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2"> |
| 433 | <div className="xs:inline hidden"> |
| 434 | {history.length === 0 && lastSessionId && !isInEdit && ( |
| 435 | <NewSessionButton |
| 436 | onClick={async () => { |
| 437 | await dispatch( |
| 438 | loadLastSession({ |
| 439 | saveCurrentSession: true, |
| 440 | }), |
| 441 | ); |
| 442 | }} |
| 443 | className="flex items-center gap-2" |
| 444 | > |
| 445 | <ArrowLeftIcon className="h-3 w-3" /> |
| 446 | <span className="text-xs">Last Session</span> |
| 447 | </NewSessionButton> |
| 448 | )} |
| 449 | </div> |
| 450 | </div> |
| 451 | <FatalErrorIndicator /> |
| 452 | {!hasDismissedExploreDialog && <ExploreDialogWatcher />} |
| 453 | {history.length === 0 && ( |
| 454 | <EmptyChatBody showOnboardingCard={onboardingCard.show} /> |
| 455 | )} |
| 456 | </div> |
| 457 | </div> |
| 458 | </> |
| 459 | ); |
| 460 | } |