| 1 | import { ChevronDownIcon } from "@heroicons/react/24/outline"; |
| 2 | import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; |
| 3 | import { renderContextItems } from "core/util/messageContent"; |
| 4 | import { useContext, useEffect, useMemo, useState } from "react"; |
| 5 | import { IdeMessengerContext } from "../../../context/IdeMessenger"; |
| 6 | import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest"; |
| 7 | import { useWebviewListener } from "../../../hooks/useWebviewListener"; |
| 8 | import { getStatusIcon } from "../../../pages/gui/ToolCallDiv/utils"; |
| 9 | import { useAppSelector } from "../../../redux/hooks"; |
| 10 | import { selectToolCallById } from "../../../redux/selectors/selectToolCalls"; |
| 11 | import { |
| 12 | selectApplyStateByStreamId, |
| 13 | selectApplyStateByToolCallId, |
| 14 | } from "../../../redux/slices/sessionSlice"; |
| 15 | import { getFontSize } from "../../../util"; |
| 16 | import Spinner from "../../gui/Spinner"; |
| 17 | import { isTerminalCodeBlock } from "../utils"; |
| 18 | import { ApplyActions } from "./ApplyActions"; |
| 19 | import { CollapsibleContainer } from "./CollapsibleContainer"; |
| 20 | import { CopyButton } from "./CopyButton"; |
| 21 | import { CreateFileButton } from "./CreateFileButton"; |
| 22 | import { FileInfo } from "./FileInfo"; |
| 23 | import { InsertButton } from "./InsertButton"; |
| 24 | import { RunInTerminalButton } from "./RunInTerminalButton"; |
| 25 | |
| 26 | export interface StepContainerPreToolbarProps { |
| 27 | showToolCallStatusIcon?: boolean; |
| 28 | codeBlockContent: string; |
| 29 | language: string | null; |
| 30 | relativeFilepath?: string; |
| 31 | itemIndex?: number; |
| 32 | codeBlockIndex: number; // To track which codeblock we are applying |
| 33 | isLastCodeblock: boolean; |
| 34 | codeBlockStreamId: string; |
| 35 | forceToolCallId?: string; // If this is defined, we will use this streamId instead of the one from the codeBlock |
| 36 | range?: string; |
| 37 | children: any; |
| 38 | expanded?: boolean; |
| 39 | disableManualApply?: boolean; |
| 40 | collapsible?: boolean; |
| 41 | } |
| 42 | |
| 43 | export function StepContainerPreToolbar({ |
| 44 | showToolCallStatusIcon, |
| 45 | codeBlockContent, |
| 46 | language, |
| 47 | relativeFilepath, |
| 48 | itemIndex, |
| 49 | codeBlockIndex, |
| 50 | isLastCodeblock, |
| 51 | codeBlockStreamId, |
| 52 | forceToolCallId, |
| 53 | range, |
| 54 | children, |
| 55 | expanded, |
| 56 | disableManualApply, |
| 57 | collapsible, |
| 58 | }: StepContainerPreToolbarProps) { |
| 59 | const ideMessenger = useContext(IdeMessengerContext); |
| 60 | const history = useAppSelector((state) => state.session.history); |
| 61 | const [isExpanded, setIsExpanded] = useState(expanded ?? true); |
| 62 | |
| 63 | const [relativeFilepathUri, setRelativeFilepathUri] = useState<string | null>( |
| 64 | null, |
| 65 | ); |
| 66 | |
| 67 | const fileExistsInput = useMemo( |
| 68 | () => (relativeFilepathUri ? { filepath: relativeFilepathUri } : null), |
| 69 | [relativeFilepathUri], |
| 70 | ); |
| 71 | |
| 72 | const { |
| 73 | result: fileExists, |
| 74 | refresh: refreshFileExists, |
| 75 | isLoading: isLoadingFileExists, |
| 76 | } = useIdeMessengerRequest("fileExists", fileExistsInput); |
| 77 | |
| 78 | const nextCodeBlockIndex = useAppSelector( |
| 79 | (state) => state.session.codeBlockApplyStates.curIndex, |
| 80 | ); |
| 81 | |
| 82 | const applyState = useAppSelector((state) => |
| 83 | selectApplyStateByStreamId(state, codeBlockStreamId), |
| 84 | ); |
| 85 | const toolCallApplyState = useAppSelector((state) => |
| 86 | selectApplyStateByToolCallId(state, forceToolCallId), |
| 87 | ); |
| 88 | |
| 89 | const toolCallState = useAppSelector((state) => |
| 90 | forceToolCallId ? selectToolCallById(state, forceToolCallId) : undefined, |
| 91 | ); |
| 92 | |
| 93 | const toolCallStatusIcon = |
| 94 | showToolCallStatusIcon && |
| 95 | (toolCallState?.status === "canceled" || |
| 96 | toolCallState?.status === "errored" || |
| 97 | toolCallState?.status === "done") ? ( |
| 98 | <div |
| 99 | className={`mr-1 h-4 w-4 ${toolCallState.output ? "cursor-pointer" : ""}`} |
| 100 | onClick={() => { |
| 101 | if (toolCallState.output) { |
| 102 | ideMessenger.post("showVirtualFile", { |
| 103 | name: "Edit output", |
| 104 | content: renderContextItems(toolCallState.output), |
| 105 | }); |
| 106 | } |
| 107 | }} |
| 108 | > |
| 109 | {getStatusIcon(toolCallState.status)} |
| 110 | </div> |
| 111 | ) : null; |
| 112 | |
| 113 | /** |
| 114 | * In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`. |
| 115 | * However, if no `relativeFilepath` is defined, then this will |
| 116 | * be the URI of the currently open file at the time the user clicks "Apply". |
| 117 | */ |
| 118 | const [appliedFileUri, setAppliedFileUri] = useState<string | undefined>( |
| 119 | undefined, |
| 120 | ); |
| 121 | |
| 122 | const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; |
| 123 | const hasFileExtension = |
| 124 | relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath); |
| 125 | |
| 126 | const isStreaming = useAppSelector((store) => store.session.isStreaming); |
| 127 | |
| 128 | const isLastItem = useMemo(() => { |
| 129 | return itemIndex === history.length - 1; |
| 130 | }, [history.length, itemIndex]); |
| 131 | |
| 132 | const isGeneratingCodeBlock = isLastItem && isLastCodeblock && isStreaming; |
| 133 | |
| 134 | // If we are creating a file, we already render that in the button |
| 135 | // so we don't want to dispaly it twice here |
| 136 | const displayFilepath = relativeFilepath ?? appliedFileUri; |
| 137 | |
| 138 | // TODO: This logic should be moved to a thunk |
| 139 | // Handle apply keyboard shortcut |
| 140 | useWebviewListener( |
| 141 | "applyCodeFromChat", |
| 142 | async () => onClickApply(), |
| 143 | [isNextCodeBlock, codeBlockContent], |
| 144 | !isNextCodeBlock, |
| 145 | ); |
| 146 | |
| 147 | useEffect(() => { |
| 148 | const getRelativeFilepathUri = async () => { |
| 149 | if (relativeFilepath) { |
| 150 | const resolvedUri = await inferResolvedUriFromRelativePath( |
| 151 | relativeFilepath, |
| 152 | ideMessenger.ide, |
| 153 | ); |
| 154 | setRelativeFilepathUri(resolvedUri); |
| 155 | } |
| 156 | }; |
| 157 | void getRelativeFilepathUri(); |
| 158 | }, [relativeFilepath, ideMessenger.ide]); |
| 159 | |
| 160 | async function getFileUriToApplyTo() { |
| 161 | // If we've already resolved a file URI (from clicking apply), use that |
| 162 | if (appliedFileUri) { |
| 163 | return appliedFileUri; |
| 164 | } |
| 165 | |
| 166 | // If we have the `relativeFilepathUri`, use that |
| 167 | if (relativeFilepathUri) { |
| 168 | return relativeFilepathUri; |
| 169 | } |
| 170 | |
| 171 | // If no filepath was provided, get the current file |
| 172 | const currentFile = await ideMessenger.ide.getCurrentFile(); |
| 173 | if (currentFile) { |
| 174 | return currentFile.path; |
| 175 | } |
| 176 | |
| 177 | return undefined; |
| 178 | } |
| 179 | |
| 180 | async function onClickApply() { |
| 181 | const fileUri = await getFileUriToApplyTo(); |
| 182 | if (!fileUri) { |
| 183 | void ideMessenger.ide.showToast( |
| 184 | "error", |
| 185 | "Could not resolve filepath to apply changes", |
| 186 | ); |
| 187 | return; |
| 188 | } |
| 189 | |
| 190 | // applyToFile will create the file if it doesn't exist |
| 191 | ideMessenger.post("applyToFile", { |
| 192 | streamId: codeBlockStreamId, |
| 193 | filepath: fileUri, |
| 194 | text: codeBlockContent, |
| 195 | }); |
| 196 | |
| 197 | setAppliedFileUri(fileUri); |
| 198 | void refreshFileExists(); |
| 199 | } |
| 200 | |
| 201 | function onClickInsertAtCursor() { |
| 202 | ideMessenger.post("insertAtCursor", { text: codeBlockContent }); |
| 203 | } |
| 204 | |
| 205 | async function handleDiffAction(action: "accept" | "reject") { |
| 206 | const filepath = await getFileUriToApplyTo(); |
| 207 | if (!filepath) { |
| 208 | void ideMessenger.ide.showToast( |
| 209 | "error", |
| 210 | `Could not resolve filepath to ${action} changes`, |
| 211 | ); |
| 212 | return; |
| 213 | } |
| 214 | |
| 215 | ideMessenger.post(`${action}Diff`, { |
| 216 | filepath, |
| 217 | streamId: codeBlockStreamId, |
| 218 | }); |
| 219 | |
| 220 | setAppliedFileUri(undefined); |
| 221 | } |
| 222 | |
| 223 | async function onClickFilename() { |
| 224 | if (appliedFileUri) { |
| 225 | ideMessenger.post("showFile", { |
| 226 | filepath: appliedFileUri, |
| 227 | }); |
| 228 | } |
| 229 | |
| 230 | if (relativeFilepath) { |
| 231 | const filepath = await inferResolvedUriFromRelativePath( |
| 232 | relativeFilepath, |
| 233 | ideMessenger.ide, |
| 234 | ); |
| 235 | |
| 236 | ideMessenger.post("showFile", { |
| 237 | filepath, |
| 238 | }); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | const renderActionButtons = () => { |
| 243 | const isPendingToolCall = toolCallApplyState?.status === "not-started"; |
| 244 | |
| 245 | if (isGeneratingCodeBlock || isPendingToolCall) { |
| 246 | const numLines = codeBlockContent.split("\n").length; |
| 247 | const plural = numLines === 1 ? "" : "s"; |
| 248 | if (isGeneratingCodeBlock) { |
| 249 | return ( |
| 250 | <span className="text-lightgray inline-flex items-center gap-2 text-right"> |
| 251 | <div> |
| 252 | <Spinner /> |
| 253 | </div> |
| 254 | </span> |
| 255 | ); |
| 256 | } else { |
| 257 | return ( |
| 258 | <span className="text-lightgray inline-flex items-center gap-2 text-right"> |
| 259 | {`${numLines} line${plural} pending`} |
| 260 | </span> |
| 261 | ); |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | if (isTerminalCodeBlock(language, codeBlockContent)) { |
| 266 | return <RunInTerminalButton command={codeBlockContent} />; |
| 267 | } |
| 268 | |
| 269 | if (isLoadingFileExists) { |
| 270 | return null; |
| 271 | } |
| 272 | |
| 273 | if (fileExists || !relativeFilepath) { |
| 274 | return ( |
| 275 | <ApplyActions |
| 276 | disableManualApply={disableManualApply} |
| 277 | applyState={toolCallApplyState ?? applyState} |
| 278 | onClickApply={onClickApply} |
| 279 | onClickAccept={() => handleDiffAction("accept")} |
| 280 | onClickReject={() => handleDiffAction("reject")} |
| 281 | /> |
| 282 | ); |
| 283 | } |
| 284 | |
| 285 | return <CreateFileButton onClick={onClickApply} />; |
| 286 | }; |
| 287 | |
| 288 | // We wait until there is an extension in the filepath to avoid rendering |
| 289 | // an incomplete filepath |
| 290 | if (relativeFilepath && !hasFileExtension) { |
| 291 | return children; |
| 292 | } |
| 293 | |
| 294 | return ( |
| 295 | <div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor !my-2 flex min-w-0 flex-col outline outline-1"> |
| 296 | <div |
| 297 | className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "rounded-t-default border-command-border border-b" : "rounded-default"}`} |
| 298 | style={{ fontSize: `${getFontSize() - 2}px` }} |
| 299 | > |
| 300 | <div className="flex max-w-[50%] flex-row items-center"> |
| 301 | {toolCallStatusIcon} |
| 302 | <ChevronDownIcon |
| 303 | data-testid="toggle-codeblock" |
| 304 | onClick={() => setIsExpanded(!isExpanded)} |
| 305 | className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${ |
| 306 | isExpanded ? "rotate-0" : "-rotate-90" |
| 307 | }`} |
| 308 | /> |
| 309 | {displayFilepath ? ( |
| 310 | <FileInfo |
| 311 | filepath={displayFilepath} |
| 312 | range={range} |
| 313 | onClick={fileExists ? onClickFilename : undefined} |
| 314 | /> |
| 315 | ) : ( |
| 316 | <span className="text-lightgray ml-2 select-none capitalize"> |
| 317 | {language} |
| 318 | </span> |
| 319 | )} |
| 320 | </div> |
| 321 | |
| 322 | <div className="flex items-center gap-2.5"> |
| 323 | {!isGeneratingCodeBlock && ( |
| 324 | <div className="xs:flex hidden items-center gap-2.5"> |
| 325 | <InsertButton onInsert={onClickInsertAtCursor} /> |
| 326 | <CopyButton text={codeBlockContent} /> |
| 327 | </div> |
| 328 | )} |
| 329 | |
| 330 | {renderActionButtons()} |
| 331 | </div> |
| 332 | </div> |
| 333 | {isExpanded && ( |
| 334 | <CollapsibleContainer collapsible={collapsible}> |
| 335 | {children} |
| 336 | </CollapsibleContainer> |
| 337 | )} |
| 338 | </div> |
| 339 | ); |
| 340 | } |