{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "elements-terminal-block",
  "type": "registry:component",
  "title": "Terminal block",
  "description": "Command output that streams line by line and ends with an exit status.",
  "registryDependencies": [
    "https://r.assistant-ui.com/base/elements-surfaces.json",
    "https://r.assistant-ui.com/base/elements-range.json",
    "https://r.assistant-ui.com/base/use-copy-to-clipboard.json"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "files": [
    {
      "type": "registry:component",
      "path": "components/assistant-ui/elements/terminal-block.tsx",
      "sourcePath": "packages/ui/src/components/react/assistant-ui/elements/terminal-block.tsx",
      "content": "\"use client\";\n\nimport { useId, useState, type ComponentProps } from \"react\";\nimport { CheckIcon, CopyIcon, Loader2Icon, XIcon } from \"lucide-react\";\nimport { useCopyToClipboard } from \"@/hooks/use-copy-to-clipboard\";\nimport { cn } from \"@/lib/utils\";\nimport { ghostButton, mono, paper } from \"./surfaces\";\nimport { clamp, take } from \"../utils/range\";\n\nexport type AnsiColor =\n  | 30\n  | 31\n  | 32\n  | 33\n  | 34\n  | 35\n  | 36\n  | 37\n  | 90\n  | 91\n  | 92\n  | 93\n  | 94\n  | 95\n  | 96\n  | 97;\n\nexport type AnsiSegment = {\n  text: string;\n  color?: AnsiColor | undefined;\n  bold: boolean;\n  dim: boolean;\n};\n\nconst ANSI_COLORS = new Set<AnsiColor>([\n  30, 31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96, 97,\n]);\n\nconst findCsiEnd = (line: string, start: number) => {\n  for (let index = start; index < line.length; index += 1) {\n    const code = line.charCodeAt(index);\n    if (code >= 0x40 && code <= 0x7e) return index;\n  }\n  return line.length;\n};\n\nconst findStringEnd = (line: string, start: number, bell: boolean) => {\n  for (let index = start; index < line.length; index += 1) {\n    if (bell && line[index] === \"\\u0007\") return index + 1;\n    if (line[index] === \"\\u001b\" && line[index + 1] === \"\\\\\") {\n      return index + 2;\n    }\n  }\n  return line.length;\n};\n\nconst applySgr = (value: string, state: Omit<AnsiSegment, \"text\">) => {\n  const parts = value.split(\";\");\n  for (let index = 0; index < parts.length; index += 1) {\n    const part = parts[index];\n    const code = part === \"\" ? 0 : Number(part);\n    if (code === 38 || code === 48) {\n      index += parts[index + 1] === \"2\" ? 4 : parts[index + 1] === \"5\" ? 2 : 1;\n    } else if (code === 0) {\n      state.color = undefined;\n      state.bold = false;\n      state.dim = false;\n    } else if (code === 1) {\n      state.bold = true;\n    } else if (code === 2) {\n      state.dim = true;\n    } else if (code === 22) {\n      state.bold = false;\n      state.dim = false;\n    } else if (code === 39) {\n      state.color = undefined;\n    } else if (ANSI_COLORS.has(code as AnsiColor)) {\n      state.color = code as AnsiColor;\n    }\n  }\n};\n\nexport function parseAnsi(line: string): AnsiSegment[] {\n  const state: Omit<AnsiSegment, \"text\"> = {\n    color: undefined,\n    bold: false,\n    dim: false,\n  };\n  const segments: AnsiSegment[] = [];\n  let index = 0;\n\n  const append = (text: string) => {\n    if (text === \"\") return;\n    const previous = segments[segments.length - 1];\n    if (\n      previous &&\n      previous.color === state.color &&\n      previous.bold === state.bold &&\n      previous.dim === state.dim\n    ) {\n      previous.text += text;\n      return;\n    }\n    segments.push({ text, ...state });\n  };\n\n  while (index < line.length) {\n    const escape = line.indexOf(\"\\u001b\", index);\n    const c1Offset = line.slice(index).search(/[\\u009b\\u009d]/);\n    const c1 = c1Offset === -1 ? -1 : index + c1Offset;\n    const next = escape === -1 ? c1 : c1 === -1 ? escape : Math.min(escape, c1);\n\n    if (next === -1) {\n      append(line.slice(index));\n      break;\n    }\n\n    append(line.slice(index, next));\n    const csi = line[next] === \"\\u009b\" || line[next + 1] === \"[\";\n    const osc = line[next] === \"\\u009d\" || line[next + 1] === \"]\";\n\n    if (csi) {\n      const start = next + (line[next] === \"\\u001b\" ? 2 : 1);\n      const end = findCsiEnd(line, start);\n      if (end === line.length) break;\n      if (line[end] === \"m\") applySgr(line.slice(start, end), state);\n      index = end + 1;\n    } else if (osc) {\n      index = findStringEnd(\n        line,\n        next + (line[next] === \"\\u001b\" ? 2 : 1),\n        true,\n      );\n    } else if (\n      line[next] === \"\\u001b\" &&\n      [\"P\", \"^\", \"_\"].includes(line[next + 1] ?? \"\")\n    ) {\n      index = findStringEnd(line, next + 2, false);\n    } else {\n      index =\n        line[next] === \"\\u001b\" &&\n        [\"(\", \")\", \"*\", \"+\", \"-\", \".\", \"/\"].includes(line[next + 1] ?? \"\")\n          ? next + 3\n          : next + 2;\n    }\n  }\n\n  return segments;\n}\n\nconst ansiColor = (color: AnsiColor, ink: boolean) => {\n  const paperColors: Record<AnsiColor, string> = {\n    30: \"text-foreground/70\",\n    31: \"text-red-600 dark:text-red-400\",\n    32: \"text-emerald-600 dark:text-emerald-400\",\n    33: \"text-amber-600 dark:text-amber-400\",\n    34: \"text-blue-600 dark:text-blue-400\",\n    35: \"text-fuchsia-600 dark:text-fuchsia-400\",\n    36: \"text-cyan-600 dark:text-cyan-400\",\n    37: \"text-foreground/85\",\n    90: \"text-muted-foreground\",\n    91: \"text-red-500 dark:text-red-400\",\n    92: \"text-emerald-500 dark:text-emerald-400\",\n    93: \"text-amber-500 dark:text-amber-400\",\n    94: \"text-blue-500 dark:text-blue-400\",\n    95: \"text-fuchsia-500 dark:text-fuchsia-400\",\n    96: \"text-cyan-500 dark:text-cyan-400\",\n    97: \"text-foreground/85\",\n  };\n  const inkColors: Record<AnsiColor, string> = {\n    30: \"text-background/70 dark:text-foreground/70\",\n    31: \"text-red-400 dark:text-red-400\",\n    32: \"text-emerald-400 dark:text-emerald-400\",\n    33: \"text-amber-300 dark:text-amber-300\",\n    34: \"text-blue-400 dark:text-blue-400\",\n    35: \"text-fuchsia-400 dark:text-fuchsia-400\",\n    36: \"text-cyan-300 dark:text-cyan-300\",\n    37: \"text-background/90 dark:text-foreground/90\",\n    90: \"text-background/50 dark:text-muted-foreground\",\n    91: \"text-red-400 dark:text-red-400\",\n    92: \"text-emerald-400 dark:text-emerald-400\",\n    93: \"text-amber-300 dark:text-amber-300\",\n    94: \"text-blue-400 dark:text-blue-400\",\n    95: \"text-fuchsia-400 dark:text-fuchsia-400\",\n    96: \"text-cyan-300 dark:text-cyan-300\",\n    97: \"text-background/90 dark:text-foreground/90\",\n  };\n\n  return (ink ? inkColors : paperColors)[color];\n};\n\nconst formatDuration = (durationMs: number) => {\n  const duration = Math.floor(clamp(durationMs, 0, Number.MAX_SAFE_INTEGER));\n  if (duration < 1000) return `${duration}ms`;\n  if (duration < 60_000) {\n    const seconds = Math.round(duration / 100) / 10;\n    return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)}s`;\n  }\n\n  const minutes = Math.floor(duration / 60_000);\n  const seconds = Math.floor((duration % 60_000) / 1000);\n  return `${minutes}m ${String(seconds).padStart(2, \"0\")}s`;\n};\n\nconst plainText = (line: string) =>\n  parseAnsi(line)\n    .map((segment) => segment.text)\n    .join(\"\");\n\nexport function TerminalBlock({\n  command,\n  lines,\n  visibleCount,\n  done,\n  variant = \"paper\",\n  exitCode: exitCodeProp,\n  stderr,\n  cwd,\n  durationMs,\n  truncated,\n  maxCollapsedLines,\n  className,\n  ...props\n}: Omit<\n  ComponentProps<\"div\">,\n  | \"children\"\n  | \"command\"\n  | \"lines\"\n  | \"visibleCount\"\n  | \"done\"\n  | \"variant\"\n  | \"exitCode\"\n  | \"stderr\"\n  | \"cwd\"\n  | \"durationMs\"\n  | \"truncated\"\n  | \"maxCollapsedLines\"\n> & {\n  command: string;\n  lines: readonly string[];\n  visibleCount: number;\n  done: boolean;\n  variant?: \"paper\" | \"ink\" | undefined;\n  exitCode?: number | undefined;\n  stderr?: readonly string[] | undefined;\n  cwd?: string | undefined;\n  durationMs?: number | undefined;\n  truncated?: boolean | undefined;\n  maxCollapsedLines?: number | undefined;\n}) {\n  const ink = variant === \"ink\";\n  const exitCode = exitCodeProp ?? 0;\n  const failed = done && exitCode !== 0;\n  const state = !done ? \"running\" : failed ? \"failed\" : \"done\";\n  const output = [\n    ...lines.map((line) => ({ line, stderr: false })),\n    ...(stderr ?? []).map((line) => ({ line, stderr: true })),\n  ];\n  const revealedLines = take(output, visibleCount);\n  const collapsedLines = Math.floor(\n    clamp(maxCollapsedLines ?? revealedLines.length, 0, revealedLines.length),\n  );\n  const canCollapse =\n    done &&\n    maxCollapsedLines !== undefined &&\n    revealedLines.length > collapsedLines;\n  const [expanded, setExpanded] = useState(false);\n  const displayedLines =\n    canCollapse && !expanded\n      ? take(revealedLines, collapsedLines)\n      : revealedLines;\n  const outputId = useId();\n  const { isCopied, copyToClipboard } = useCopyToClipboard();\n\n  return (\n    <div\n      className={cn(\n        ink ? \"bg-foreground dark:bg-popover\" : paper,\n        \"w-full max-w-md overflow-hidden rounded-2xl font-mono text-xs\",\n        className,\n      )}\n      {...props}\n      data-slot=\"terminal-block\"\n      data-state={state}\n    >\n      <div className=\"flex items-center justify-between gap-3 px-4 pt-3 pb-1.5\">\n        <span\n          className={cn(\n            \"min-w-0 break-words\",\n            ink\n              ? \"text-background/90 dark:text-foreground/90\"\n              : \"text-foreground/90\",\n          )}\n        >\n          {cwd ? (\n            <span\n              className={cn(\n                ink\n                  ? \"text-background/40 dark:text-muted-foreground\"\n                  : \"text-muted-foreground\",\n              )}\n            >\n              {cwd} ${\" \"}\n            </span>\n          ) : null}\n          {command}\n        </span>\n        {done ? (\n          <div className=\"flex shrink-0 items-center gap-1\">\n            {failed ? (\n              <XIcon className=\"size-3 text-red-600 dark:text-red-400\" />\n            ) : (\n              <CheckIcon className=\"size-3 text-emerald-500\" />\n            )}\n            <span\n              className={cn(\n                mono,\n                failed\n                  ? \"text-red-600 dark:text-red-400\"\n                  : ink\n                    ? \"text-background/40 dark:text-muted-foreground\"\n                    : \"text-muted-foreground\",\n              )}\n            >\n              exit {exitCode}\n            </span>\n            {durationMs !== undefined ? (\n              <span\n                className={cn(\n                  mono,\n                  ink\n                    ? \"text-background/40 dark:text-muted-foreground\"\n                    : \"text-muted-foreground\",\n                )}\n              >\n                {formatDuration(durationMs)}\n              </span>\n            ) : null}\n            {output.length > 0 ? (\n              <button\n                type=\"button\"\n                aria-label=\"Copy output\"\n                onClick={() =>\n                  copyToClipboard(\n                    output.map(({ line }) => plainText(line)).join(\"\\n\"),\n                  )\n                }\n                className={cn(\n                  ghostButton,\n                  \"size-6\",\n                  ink &&\n                    \"text-background/45 hover:text-background dark:text-muted-foreground dark:hover:text-foreground\",\n                )}\n              >\n                {isCopied ? (\n                  <CheckIcon className=\"size-3.5 text-emerald-500\" />\n                ) : (\n                  <CopyIcon className=\"size-3.5\" />\n                )}\n              </button>\n            ) : null}\n          </div>\n        ) : (\n          <Loader2Icon\n            className={cn(\n              \"size-3 animate-spin motion-reduce:animate-none\",\n              ink\n                ? \"text-background/35 dark:text-muted-foreground\"\n                : \"text-muted-foreground\",\n            )}\n          />\n        )}\n      </div>\n      <div\n        className={cn(\n          \"flex min-h-[8.5rem] flex-col gap-1 px-4 pt-1 pb-3.5\",\n          ink\n            ? \"text-background/55 dark:text-muted-foreground\"\n            : \"text-muted-foreground\",\n        )}\n      >\n        <div id={outputId} className=\"flex flex-col gap-1\">\n          {displayedLines.map(({ line, stderr: isStderr }, index) => {\n            const isLast = index === revealedLines.length - 1;\n            return (\n              <div\n                key={`${index}-${line}`}\n                className={cn(\n                  \"fade-in animate-in fill-mode-both break-words whitespace-pre-wrap duration-300 motion-reduce:animate-none\",\n                  isStderr\n                    ? \"text-red-600 dark:text-red-400\"\n                    : isLast &&\n                        (ink\n                          ? \"text-background/90 dark:text-foreground/90\"\n                          : \"text-foreground/90\"),\n                )}\n              >\n                {parseAnsi(line).map((segment, segmentIndex) => (\n                  <span\n                    key={segmentIndex}\n                    className={cn(\n                      !isStderr &&\n                        segment.color !== undefined &&\n                        ansiColor(segment.color, ink),\n                      segment.bold && \"font-bold\",\n                      segment.dim && \"opacity-60\",\n                    )}\n                  >\n                    {segment.text}\n                  </span>\n                ))}\n              </div>\n            );\n          })}\n        </div>\n        {canCollapse ? (\n          <button\n            type=\"button\"\n            aria-expanded={expanded}\n            aria-controls={outputId}\n            onClick={() => setExpanded((value) => !value)}\n            className={cn(\n              ghostButton,\n              \"h-7 self-start px-2 text-xs\",\n              ink &&\n                \"text-background/45 hover:text-background dark:text-muted-foreground dark:hover:text-foreground\",\n            )}\n          >\n            {expanded ? \"Show less\" : `Show all ${revealedLines.length} lines`}\n          </button>\n        ) : null}\n        {truncated ? (\n          <span\n            className={cn(\n              mono,\n              ink\n                ? \"text-background/35 dark:text-muted-foreground\"\n                : \"text-muted-foreground\",\n            )}\n          >\n            output truncated\n          </span>\n        ) : null}\n        {!done && (\n          <span\n            aria-hidden\n            className=\"inline-block h-3 w-1.5 animate-pulse bg-blue-500/70 motion-reduce:animate-none dark:bg-blue-400/70\"\n          />\n        )}\n      </div>\n    </div>\n  );\n}\n"
    }
  ]
}