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