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