Elffuss BraidHub

kikocis/continue public

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