Skip to content
Shaken UI
Sign in

Terminal

Save

A command an agent runs with its plain text output streaming in, the exit code and duration, a copy button, and auto scroll that pauses when the reader scrolls up.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Terminal preview

~/acme/web pnpm build

Running
Waiting for output

Installation

npx @shakenui/cli add terminal

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add terminal --dry-run

Usage

terminal-example.tsx
import { Terminal } from "@/components/shaken/agent/terminal";

const install = `Lockfile is up to date, resolution step is skipped
Progress: resolved 412, reused 409, downloaded 3, added 3, done

dependencies:
+ zod 3.24.1

Done in 2.3s using pnpm v10.4.1`;

const typecheck = `src/billing/proration.ts:58:11 - error TS2322: Type 'number | undefined' is not assignable to type 'number'.

58     const days: number = period.days;
             ~~~~

Found 1 error in src/billing/proration.ts:58`;

export default function TerminalExample() {
  return (
    <div className="grid w-full max-w-xl gap-3">
      <Terminal command="pnpm add zod" cwd="~/acme/web" status="success" output={install} durationMs={2310} />
      <Terminal command="pnpm tsc --noEmit" cwd="~/acme/web" status="error" exitCode={2} output={typecheck} durationMs={6840} />
    </div>
  );
}

API

PropTypeDefaultDescription
commandstring—The command, shown after a $ prompt.
outputstring—Plain text output so far (no ANSI codes). Append to it while running.
status"queued" | "running" | "success" | "error"—Running shows the Working mark and a caret; the end states show Exit and the code.
exitCodenumber—Defaults to 0 on success and 1 on error.
durationMsnumber—Elapsed time, shown once the command ends.
cwdstring—Working directory before the prompt.
maxHeightnumber288Output height in pixels before it scrolls.

Accessibility

  • The output is a focusable role log region, so keyboard users can scroll it and screen readers hear new lines politely.
  • The status is a live region that reads Running, then Exit 0 or Exit 1; failure also turns the border and exit text red and swaps the glyph to an x.
  • Auto scroll follows new output only while the reader is at the bottom; a Jump to latest button appears otherwise and scrolls instantly under reduced motion.
  • The copy button is labelled Copy command and output and announces Copied. The caret blink and the Working mark hold still with reduced motion.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/terminal.tsxterminal
  • Also installs agent-state@0.1.0registry dependency
  • Also installs step-list@0.3.0registry dependency
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/terminal/0.1.0.json.

agent/terminal.tsxShow
agent/terminal.tsx
"use client";

import { type ComponentProps, useEffect, useLayoutEffect, useRef, useState } from "react";
import { AgentState } from "./agent-state";
import { StatusGlyph } from "./step-list";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";

export type TerminalStatus = "queued" | "running" | "success" | "error";

export interface TerminalProps extends Omit<ComponentProps<"section">, "children"> {
  /** The command the agent runs, without the prompt. */
  command: string;
  /** Plain text output so far (no ANSI codes). Append to it while the command runs. */
  output?: string;
  status: TerminalStatus;
  /** Exit code once the command ends. Defaults to 0 on success and 1 on error. */
  exitCode?: number;
  /** Elapsed time, shown once the command ends. */
  durationMs?: number;
  /** Working directory shown before the prompt. */
  cwd?: string;
  /** Output height before it scrolls, in pixels. */
  maxHeight?: number;
}

/**
 * A command an agent runs, with its output streaming in. The output follows new lines until the
 * reader scrolls up, then a "Jump to latest" button brings them back. Shows the exit code,
 * duration, and a copy button once the command ends.
 */
export function Terminal({
  command,
  output = "",
  status,
  exitCode,
  durationMs,
  cwd,
  maxHeight = 288,
  className,
  ...props
}: TerminalProps) {
  const running = status === "running";
  const finished = status === "success" || status === "error";
  const code = exitCode ?? (status === "success" ? 0 : 1);
  const scroller = useRef<HTMLPreElement>(null);
  const followingRef = useRef(true);
  const [following, setFollowing] = useState(true);

  useLayoutEffect(() => {
    const element = scroller.current;
    if (element && followingRef.current) element.scrollTop = element.scrollHeight;
  }, [output]);

  useEffect(() => {
    const element = scroller.current;
    if (!element) return;
    const onScroll = () => {
      const atBottom = element.scrollHeight - element.scrollTop - element.clientHeight < 16;
      followingRef.current = atBottom;
      setFollowing(atBottom);
    };
    element.addEventListener("scroll", onScroll, { passive: true });
    return () => element.removeEventListener("scroll", onScroll);
  }, []);

  function jumpToLatest() {
    const element = scroller.current;
    if (!element) return;
    followingRef.current = true;
    setFollowing(true);
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    element.scrollTo({ top: element.scrollHeight, behavior: reduce ? "auto" : "smooth" });
  }

  return (
    <section
      aria-label={`Terminal: ${command}`}
      aria-busy={running || undefined}
      data-status={status}
      className={cx(
        "overflow-hidden rounded-xl border bg-white text-left text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
        "transition-[border-color] duration-200 motion-reduce:transition-none",
        "dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
        status === "error" ? "border-red-500/35" : "border-zinc-950/10 dark:border-white/10",
        className,
      )}
      {...props}
    >
      <header className="flex flex-wrap items-start gap-x-3 gap-y-0.5 py-2.5 pr-2.5 pl-4">
        <p className="min-w-[min(100%,14rem)] flex-1 py-1 font-mono text-[13px] leading-5 [overflow-wrap:anywhere]">
          {cwd ? <span className="text-zinc-500">{cwd} </span> : null}
          <span aria-hidden="true" className="text-zinc-400 select-none dark:text-zinc-600">
            ${" "}
          </span>
          <span className={status === "queued" ? "text-zinc-500" : "text-zinc-950 dark:text-white"}>{command}</span>
        </p>
        <div className="ml-auto flex shrink-0 items-center gap-2.5 pt-0.5">
          {finished && durationMs != null ? (
            <span className={`font-mono text-xs text-zinc-500 tabular-nums transition-opacity duration-300 ${ease} starting:opacity-0 motion-reduce:transition-none`}>
              {formatDuration(durationMs)}
            </span>
          ) : null}
          {running ? (
            <AgentState status size="sm" activity="working" label="Running" />
          ) : (
            <span role="status" className="inline-flex h-6 items-center gap-1.5 text-xs">
              <StatusGlyph key={status} kind={status === "queued" ? "queued" : status === "success" ? "success" : "failed"} />
              <span
                className={cx(
                  "font-mono tabular-nums",
                  status === "error" ? "text-red-600 dark:text-red-400" : status === "queued" ? "text-zinc-500" : "text-zinc-600 dark:text-zinc-400",
                )}
              >
                {status === "queued" ? "Queued" : `Exit ${code}`}
              </span>
            </span>
          )}
          <CopyButton text={output ? `$ ${command}\n${output}` : `$ ${command}`} label="Copy command and output" />
        </div>
      </header>
      {status !== "queued" ? (
        <div className="relative border-t border-zinc-950/[0.07] dark:border-white/[0.08]">
          <pre
            ref={scroller}
            role="log"
            aria-label="Output"
            tabIndex={0}
            className={cx(
              "overflow-auto px-4 py-3 font-mono text-xs leading-relaxed whitespace-pre-wrap text-zinc-700 [overflow-wrap:anywhere] dark:text-zinc-300",
              "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
            )}
            style={{ maxHeight }}
          >
            {output ? output : running ? <span className="text-zinc-500">Waiting for output</span> : <span className="text-zinc-500">No output</span>}
            {running ? (
              <span
                aria-hidden="true"
                className="ml-px inline-block h-[1.1em] w-[0.55em] translate-y-[0.2em] bg-zinc-950/70 motion-safe:animate-pulse dark:bg-white/75"
              />
            ) : null}
          </pre>
          {!following ? (
            <button
              type="button"
              onClick={jumpToLatest}
              className={cx(
                "absolute bottom-2.5 left-1/2 inline-flex h-7 -translate-x-1/2 cursor-pointer items-center gap-1.5 rounded-full px-3 text-xs font-medium",
                "border border-zinc-950/10 bg-white text-zinc-700 shadow-[0_4px_12px_-4px_rgb(0_0_0/0.18)] hover:text-zinc-950",
                "dark:border-white/15 dark:bg-black dark:text-zinc-300 dark:shadow-[0_8px_24px_-8px_rgb(0_0_0/1)] dark:hover:text-white",
                `transition-[opacity,scale,color] duration-160 ${ease} starting:scale-96 starting:opacity-0 motion-reduce:transition-none`,
                "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
              )}
            >
              <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-3.5">
                <path d="M8 3.5v9m0 0-3.5-3.5M8 12.5l3.5-3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              Jump to latest
            </button>
          ) : null}
        </div>
      ) : null}
    </section>
  );
}

/** An icon button that copies text and confirms with a check for 1.5s; the confirmation is announced. */
function CopyButton({ text, label }: { text: string; label: string }) {
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);

  async function copy() {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      clearTimeout(timer.current);
      timer.current = setTimeout(() => setCopied(false), 1500);
    } catch {
      setCopied(false);
    }
  }

  return (
    <button
      type="button"
      onClick={copy}
      aria-label={label}
      className={cx(
        "inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-zinc-500",
        "transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
        "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
        "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
      )}
    >
      <svg
        key={copied ? "copied" : "copy"}
        aria-hidden="true"
        viewBox="0 0 16 16"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        className={cx(
          "size-4 transition-[opacity,scale] duration-200 starting:scale-90 starting:opacity-0 motion-reduce:transition-none",
          ease,
          copied && "text-emerald-600 dark:text-emerald-400",
        )}
      >
        {copied ? (
          <path d="m3.75 8.5 2.75 2.75 5.75-6.5" />
        ) : (
          <>
            <rect x="5.25" y="5.25" width="8" height="8" rx="1.75" />
            <path d="M10.75 5.25V3.5c0-.97-.78-1.75-1.75-1.75H3.5c-.97 0-1.75.78-1.75 1.75V9c0 .97.78 1.75 1.75 1.75h1.75" />
          </>
        )}
      </svg>
      <span className="sr-only" aria-live="polite">
        {copied ? "Copied" : ""}
      </span>
    </button>
  );
}

function formatDuration(ms: number): string {
  if (ms < 1000) return `${Math.round(ms)} ms`;
  if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
  const minutes = Math.floor(ms / 60_000);
  return `${minutes}m ${Math.round((ms % 60_000) / 1000)}s`;
}