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