Elffuss BraidHub

kikocis/continue public

main · 14.2 KiBRawPermalink
1import { ChevronDownIcon } from "@heroicons/react/24/outline";
2import Anser, { AnserJsonEntry } from "anser";
3import { ToolCallState } from "core";
4import { escapeCarriageReturn } from "escape-carriage";
5import { useMemo, useState } from "react";
6import styled, { keyframes } from "styled-components";
7import { useAppDispatch } from "../../redux/hooks";
8import { moveTerminalProcessToBackground } from "../../redux/thunks/moveTerminalProcessToBackground";
9import { getFontSize } from "../../util";
10import { CopyButton } from "../StyledMarkdownPreview/StepContainerPreToolbar/CopyButton";
11import { RunInTerminalButton } from "../StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton";
12import { ButtonContent, SpoilerButton } from "../ui/SpoilerButton";
13
14const blinkCursor = keyframes`
15 0%, 50% { opacity: 1; }
16 51%, 100% { opacity: 0; }
17`;
18
19const BlinkingCursor = styled.span`
20 &::after {
21 content: "█";
22 animation: ${blinkCursor} 1s infinite;
23 color: var(--foreground);
24 }
25`;
26
27const AnsiSpan = styled.span<{
28 bg?: string;
29 fg?: string;
30 decoration?: string;
31}>`
32 ${({ bg }) => bg && `background-color: rgb(${bg});`}
33 ${({ fg }) => fg && `color: rgb(${fg});`}
34 ${({ decoration }) => {
35 switch (decoration) {
36 case "bold":
37 return "font-weight: bold;";
38 case "dim":
39 return "opacity: 0.5;";
40 case "italic":
41 return "font-style: italic;";
42 case "hidden":
43 return "visibility: hidden;";
44 case "strikethrough":
45 return "text-decoration: line-through;";
46 case "underline":
47 return "text-decoration: underline;";
48 case "blink":
49 return "text-decoration: blink;";
50 default:
51 return "";
52 }
53 }}
54`;
55
56const AnsiLink = styled.a`
57 color: var(--link);
58 text-decoration: none;
59 &:hover {
60 text-decoration: underline;
61 }
62`;
63
64const StyledTerminalContainer = styled.div<{
65 fontSize?: number;
66}>`
67 background-color: var(--background);
68 font-family:
69 ui-sans-serif,
70 system-ui,
71 -apple-system,
72 BlinkMacSystemFont,
73 "Segoe UI",
74 Roboto,
75 "Helvetica Neue",
76 Arial,
77 "Noto Sans",
78 sans-serif;
79 font-size: ${(props) => props.fontSize || getFontSize()}px;
80 color: var(--foreground);
81 line-height: 1.5;
82
83 > *:last-child {
84 margin-bottom: 0;
85 }
86`;
87
88const TerminalContent = styled.div`
89 pre {
90 white-space: pre-wrap;
91 max-width: calc(100vw - 24px);
92 overflow-x: scroll;
93 overflow-y: hidden;
94 padding: 8px;
95 margin: 0;
96 }
97
98 code {
99 span.line:empty {
100 display: none;
101 }
102 word-wrap: break-word;
103 border-radius: 0.5rem;
104 background-color: var(--editor-background);
105 font-size: ${getFontSize() - 2}px;
106 font-family:
107 ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono",
108 Menlo, monospace;
109 }
110
111 code:not(pre > code) {
112 font-family:
113 ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono",
114 Menlo, monospace;
115 color: var(--input-placeholder);
116 }
117`;
118
119function ansiToJSON(
120 input: string,
121 use_classes: boolean = false,
122): AnserJsonEntry[] {
123 input = escapeCarriageReturn(fixBackspace(input));
124 return Anser.ansiToJson(input, {
125 json: true,
126 remove_empty: true,
127 use_classes,
128 });
129}
130
131function createClass(bundle: AnserJsonEntry): string | null {
132 let classNames: string = "";
133
134 if (bundle.bg) {
135 classNames += `${bundle.bg}-bg `;
136 }
137 if (bundle.fg) {
138 classNames += `${bundle.fg}-fg `;
139 }
140 if (bundle.decoration) {
141 classNames += `ansi-${bundle.decoration} `;
142 }
143
144 if (classNames === "") {
145 return null;
146 }
147
148 classNames = classNames.substring(0, classNames.length - 1);
149 return classNames;
150}
151
152function convertBundleIntoReact(
153 linkify: boolean,
154 useClasses: boolean,
155 bundle: AnserJsonEntry,
156 key: number,
157): JSX.Element {
158 const className = useClasses ? createClass(bundle) : null;
159 const decorationProp = bundle.decoration
160 ? String(bundle.decoration)
161 : undefined;
162
163 if (!linkify) {
164 return (
165 <AnsiSpan
166 key={key}
167 className={className || undefined}
168 bg={useClasses ? undefined : bundle.bg}
169 fg={useClasses ? undefined : bundle.fg}
170 decoration={decorationProp}
171 >
172 {bundle.content}
173 </AnsiSpan>
174 );
175 }
176
177 const content: React.ReactNode[] = [];
178 const linkRegex =
179 /(\s|^)(https?:\/\/(?:www\.|(?!www))[^\s.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/g;
180
181 let index = 0;
182 let match: RegExpExecArray | null;
183 while ((match = linkRegex.exec(bundle.content)) !== null) {
184 const [, pre, url] = match;
185
186 const startIndex = match.index + pre.length;
187 if (startIndex > index) {
188 content.push(bundle.content.substring(index, startIndex));
189 }
190
191 const href = url.startsWith("www.") ? `http://${url}` : url;
192
193 content.push(
194 <AnsiLink key={index} href={href} target="_blank">
195 {url}
196 </AnsiLink>,
197 );
198
199 index = linkRegex.lastIndex;
200 }
201
202 if (index < bundle.content.length) {
203 content.push(bundle.content.substring(index));
204 }
205
206 return (
207 <AnsiSpan
208 key={key}
209 className={className || undefined}
210 bg={useClasses ? undefined : bundle.bg}
211 fg={useClasses ? undefined : bundle.fg}
212 decoration={decorationProp}
213 >
214 {content}
215 </AnsiSpan>
216 );
217}
218
219function fixBackspace(txt: string) {
220 let tmp = txt;
221 do {
222 txt = tmp;
223 tmp = txt.replace(/[^\n]\x08/gm, "");
224 } while (tmp.length < txt.length);
225 return txt;
226}
227
228function AnsiRenderer({
229 children,
230 linkify = false,
231}: {
232 children?: string;
233 linkify?: boolean;
234}) {
235 const ansiContent = ansiToJSON(children ?? "", false).map((bundle, i) =>
236 convertBundleIntoReact(linkify, false, bundle, i),
237 );
238
239 return <>{ansiContent}</>;
240}
241
242interface StatusIconProps {
243 status: "running" | "completed" | "failed" | "background";
244}
245
246function StatusIcon({ status }: StatusIconProps) {
247 const getStatusColor = () => {
248 switch (status) {
249 case "running":
250 return "bg-success";
251 case "completed":
252 return "bg-success";
253 case "background":
254 return "bg-accent";
255 case "failed":
256 return "bg-error";
257 default:
258 return "bg-success";
259 }
260 };
261
262 return (
263 <span
264 className={`mr-2 h-2 w-2 rounded-full ${getStatusColor()} ${
265 status === "running" ? "animate-pulse" : ""
266 }`}
267 />
268 );
269}
270
271interface IndicatorOnlyProps {
272 hiddenLinesCount: number;
273 isExpanded: boolean;
274 onToggle: () => void;
275}
276
277function IndicatorOnly({
278 hiddenLinesCount,
279 isExpanded,
280 onToggle,
281}: IndicatorOnlyProps) {
282 return (
283 <div className="flex justify-center">
284 <SpoilerButton onClick={onToggle}>
285 <ButtonContent>
286 <span>
287 {isExpanded ? "Collapse" : `+${hiddenLinesCount} more lines`}
288 </span>
289 <ChevronDownIcon
290 className={`h-3 w-3 ${isExpanded ? "rotate-180" : ""}`}
291 />
292 </ButtonContent>
293 </SpoilerButton>
294 </div>
295 );
296}
297
298interface CollapsibleOutputContainerProps {
299 limitedContent: string;
300 fullContent: string;
301 isExpanded: boolean;
302 onToggle: () => void;
303}
304
305function CollapsibleOutputContainer({
306 limitedContent,
307 fullContent,
308 isExpanded,
309 onToggle,
310}: CollapsibleOutputContainerProps) {
311 return (
312 <div className="relative">
313 {/* Gradient overlay when collapsed */}
314 {!isExpanded && (
315 <div className="from-editor pointer-events-none absolute left-0 right-0 top-0 z-[5] h-[100px] rounded-t-md bg-gradient-to-b to-transparent" />
316 )}
317
318 <div onClick={onToggle} className="cursor-pointer">
319 <div>
320 <AnsiRenderer linkify>
321 {isExpanded ? fullContent : limitedContent}
322 </AnsiRenderer>
323 </div>
324 </div>
325 </div>
326 );
327}
328
329interface UnifiedTerminalCommandProps {
330 command: string;
331 output?: string;
332 status?: "running" | "completed" | "failed" | "background";
333 statusMessage?: string;
334 toolCallState?: ToolCallState;
335 toolCallId?: string;
336 displayLines?: number;
337}
338
339export function UnifiedTerminalCommand({
340 command,
341 output = "",
342 status = "completed",
343 statusMessage = "",
344 toolCallState,
345 toolCallId,
346 displayLines = 15,
347}: UnifiedTerminalCommandProps) {
348 const dispatch = useAppDispatch();
349 const [isExpanded, setIsExpanded] = useState(true);
350 const [outputExpanded, setOutputExpanded] = useState(false);
351
352 // Determine running state
353 const isRunning = toolCallState?.status === "calling" || status === "running";
354 const hasOutput = output.length > 0;
355
356 // Process terminal content for line limiting
357 const processedTerminalContent = useMemo(() => {
358 if (!output) {
359 return {
360 fullContent: "",
361 limitedContent: "",
362 totalLines: 0,
363 isLimited: false,
364 hiddenLinesCount: 0,
365 };
366 }
367
368 const lines = output.split("\n");
369 const totalLines = lines.length;
370
371 if (totalLines > displayLines) {
372 const lastLines = lines.slice(-displayLines);
373 return {
374 fullContent: output,
375 limitedContent: lastLines.join("\n"),
376 totalLines,
377 isLimited: true,
378 hiddenLinesCount: totalLines - displayLines,
379 };
380 }
381
382 return {
383 fullContent: output,
384 limitedContent: output,
385 totalLines,
386 isLimited: false,
387 hiddenLinesCount: 0,
388 };
389 }, [output, displayLines]);
390
391 // Determine status type
392 let statusType: "running" | "completed" | "failed" | "background" = status;
393 if (isRunning) {
394 statusType = "running";
395 } else if (statusMessage?.includes("failed")) {
396 statusType = "failed";
397 } else if (statusMessage?.includes("background")) {
398 statusType = "background";
399 }
400
401 const handleMoveToBackground = () => {
402 if (toolCallId) {
403 void dispatch(
404 moveTerminalProcessToBackground({
405 toolCallId,
406 }),
407 );
408 }
409 };
410
411 // Create combined content for copying (command + output)
412 const copyContent = useMemo(() => {
413 let content = `$ ${command}`;
414 if (hasOutput) {
415 content += `\n\n${output}`;
416 }
417 return content;
418 }, [command, output, hasOutput]);
419
420 return (
421 <StyledTerminalContainer
422 fontSize={getFontSize()}
423 className="mx-2 mb-4"
424 data-testid="terminal-container"
425 >
426 <div className="outline-command-border rounded-default bg-editor !my-2 flex min-w-0 flex-col outline outline-1">
427 {/* Toolbar */}
428 <div
429 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 ${
430 isExpanded
431 ? "rounded-t-default border-command-border border-b"
432 : "rounded-default"
433 }`}
434 style={{ fontSize: `${getFontSize() - 2}px` }}
435 >
436 <div className="flex max-w-[50%] flex-row items-center">
437 <ChevronDownIcon
438 onClick={() => setIsExpanded(!isExpanded)}
439 className={`text-description h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${
440 isExpanded ? "rotate-0" : "-rotate-90"
441 }`}
442 />
443 <span className="text-description ml-2 select-none">Terminal</span>
444 </div>
445
446 <div className="flex items-center gap-2.5">
447 {!isRunning && (
448 <div className="xs:flex hidden items-center gap-2.5">
449 <CopyButton text={copyContent} />
450 <RunInTerminalButton command={command} />
451 </div>
452 )}
453 </div>
454 </div>
455
456 {/* Content */}
457 {isExpanded && (
458 <TerminalContent>
459 <pre className="bg-editor">
460 <code>
461 {/* Command is always visible */}
462 <div className="text-terminal pb-2">$ {command}</div>
463
464 {/* Running state with cursor */}
465 {isRunning && !hasOutput && (
466 <div className="mt-1 flex items-center gap-1">
467 <BlinkingCursor />
468 </div>
469 )}
470
471 {/* Output with optional collapsible functionality */}
472 {hasOutput && (
473 <div className="mt-1">
474 {/* Expand/Collapse indicator positioned between command and output */}
475 {processedTerminalContent.isLimited && (
476 <IndicatorOnly
477 hiddenLinesCount={
478 processedTerminalContent.hiddenLinesCount
479 }
480 isExpanded={outputExpanded}
481 onToggle={() => setOutputExpanded(!outputExpanded)}
482 />
483 )}
484
485 <div className="pt-2">
486 {processedTerminalContent.isLimited ? (
487 <CollapsibleOutputContainer
488 limitedContent={
489 processedTerminalContent.limitedContent
490 }
491 fullContent={processedTerminalContent.fullContent}
492 isExpanded={outputExpanded}
493 onToggle={() => setOutputExpanded(!outputExpanded)}
494 />
495 ) : (
496 <div>
497 <AnsiRenderer linkify>
498 {processedTerminalContent.fullContent}
499 </AnsiRenderer>
500 </div>
501 )}
502 </div>
503 </div>
504 )}
505 </code>
506 </pre>
507 </TerminalContent>
508 )}
509
510 {/* Status information */}
511 {(statusMessage || isRunning) && (
512 <div
513 className="text-description flex items-center px-2 pb-2 pt-2 text-xs"
514 style={{
515 borderTop:
516 "1px solid var(--vscode-commandCenter-inactiveBorder, #555555)",
517 }}
518 >
519 <StatusIcon status={statusType} />
520 {isRunning ? "Running" : statusMessage}
521 {isRunning && toolCallId && (
522 <a
523 href="#"
524 onClick={(e) => {
525 e.preventDefault();
526 handleMoveToBackground();
527 }}
528 className="text-link ml-3 cursor-pointer text-xs no-underline hover:underline"
529 >
530 Move to background
531 </a>
532 )}
533 </div>
534 )}
535 </div>
536 </StyledTerminalContainer>
537 );
538}