Skip to content

Terminal

Shows a command the agent ran, with its output streaming in and its exit code.

Run the checks, then build the app.
> acme-chat@0.1.0 build
> next build

   ▲ Next.js 16.3.0
   Creating an optimized production build ...
 ✓ Compiled successfully in 4.2s
 ✓ Generating static pages (12/12)

Route (app)                Size  First Load JS
┌ ○ /                     1.9 kB       112 kB
└ ƒ /api/chat              141 B       102 kB

Lint and tests pass, and the build compiled both routes.

Installation

pnpm dlx shadcn@latest add @silkware/ai-terminal

To copy the pattern by hand, install the components it composes:

pnpm dlx shadcn@latest add @silkware/bubble @silkware/button @silkware/code-block @silkware/message @silkware/trace

Then the packages:

pnpm add ai @ai-sdk/react @shadcn/helpers lucide-react

Copy the source into components/ai-elements/terminal.tsx. The file also needs @/lib/ai:

components/ai-elements/terminal.tsx
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"import type { UIMessage } from "ai"import { TerminalIcon } from "lucide-react"
import { createChat, getMessageText } from "@/lib/ai"import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Button } from "@/components/ui/button"import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import { Message, MessageContent } from "@/components/ui/message"import {  Trace,  TraceCollapsible,  TraceCollapsibleContent,  TraceCollapsibleTrigger,  TraceIcon,  TraceLine,  TraceTitle,} from "@/components/ui/trace"
type ChatMessage = UIMessage<  unknown,  {    terminal: { output: string }  },  {    runCommand: {      input: { command: string }      output: { exitCode: number }    }  }>
type ToolPart = Extract<  ChatMessage["parts"][number],  { type: "tool-runCommand" }>
const COMMANDS = [  {    id: "lint",    command: "pnpm lint",    output: ["> acme-chat@0.1.0 lint", "> eslint ."],  },  {    id: "test",    command: "pnpm test",    output: [      "> acme-chat@0.1.0 test",      "> vitest run",      "",      " ✓ lib/ai.test.ts (6 tests) 41ms",      " ✓ components/chat.test.tsx (9 tests) 212ms",      "",      " Test Files  2 passed (2)",      "      Tests  15 passed (15)",    ],  },  {    id: "build",    command: "pnpm build",    output: [      "> acme-chat@0.1.0 build",      "> next build",      "",      "   ▲ Next.js 16.3.0",      "   Creating an optimized production build ...",      " ✓ Compiled successfully in 4.2s",      " ✓ Generating static pages (12/12)",      "",      "Route (app)                Size  First Load JS",      "┌ ○ /                     1.9 kB       112 kB",      "└ ƒ /api/chat              141 B       102 kB",    ],  },]
const chat = createChat<ChatMessage>()  .user("Run the checks, then build the app.")  .assistant(({ writer }) => {    for (const { id, command, output } of COMMANDS) {      const tool = writer.tool("runCommand", {        toolCallId: id,        input: { command },      })
      output.forEach((_, index) => {        writer          .data({            type: "data-terminal",            id,            data: { output: output.slice(0, index + 1).join("\n") },          })          .sleep(200)      })
      tool.output({ exitCode: 0 })    }
    writer.text("Lint and tests pass, and the build compiled both routes.")  })
const transcript = chat.get()const [question] = chat.get(1)const transport = chat.transport({ delayMs: 20 })
function getTitle(part: ToolPart, running: boolean) {  const command = part.input?.command
  if (part.state === "output-available") {    return part.output.exitCode === 0      ? `Ran ${command}`      : `${command} exited with code ${part.output.exitCode}`  }
  return running ? `Running ${command}` : `Failed to run ${command}`}
function getOutput(message: ChatMessage, toolCallId: string) {  for (const part of message.parts) {    if (part.type === "data-terminal" && part.id === toolCallId) {      return part.data.output    }  }
  return ""}
function CommandRow({  part,  output,  streaming,  defaultExpanded,}: {  part: ToolPart  output: string  streaming: boolean  defaultExpanded?: boolean}) {  const [open, setOpen] = React.useState(defaultExpanded)  const running =    streaming &&    (part.state === "input-streaming" || part.state === "input-available")  const failed =    !running &&    (part.state !== "output-available" || part.output.exitCode !== 0)
  return (    <TraceCollapsible      isExpanded={open ?? (running && output.length > 0)}      onExpandedChange={setOpen}    >      <TraceCollapsibleTrigger>        <TraceLine status={running ? "running" : failed ? "error" : undefined}>          <TraceIcon>            <TerminalIcon />          </TraceIcon>          <TraceTitle>{getTitle(part, running)}</TraceTitle>        </TraceLine>      </TraceCollapsibleTrigger>      <TraceCollapsibleContent>        <CodeBlock size="sm">          <CodeBlockContent wrap className="max-h-64">            {part.state === "output-error" ? part.errorText : output}          </CodeBlockContent>        </CodeBlock>      </TraceCollapsibleContent>    </TraceCollapsible>  )}
export function TerminalDemo() {  const { messages, sendMessage, setMessages, status } = useChat({    messages: transcript,    transport,  })  const busy = status === "submitted" || status === "streaming"
  return (    <div className="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">      {messages.map((message) => {        if (message.role === "user") {          return (            <Message key={message.id} align="end">              <MessageContent>                <Bubble align="end" variant="muted">                  <BubbleContent>{getMessageText(message)}</BubbleContent>                </Bubble>              </MessageContent>            </Message>          )        }
        const streaming = busy && message === messages.at(-1)        const tools = message.parts.filter(          (part) => part.type === "tool-runCommand"        )        const text = getMessageText(message)
        return (          <Message key={message.id}>            <MessageContent className="gap-4">              {tools.length > 0 && (                <Trace>                  {tools.map((part) => (                    <CommandRow                      key={part.toolCallId}                      part={part}                      output={getOutput(message, part.toolCallId)}                      streaming={streaming}                      defaultExpanded={busy ? undefined : part === tools.at(-1)}                    />                  ))}                </Trace>              )}              {text && <p>{text}</p>}            </MessageContent>          </Message>        )      })}      {!busy && (        <Button          variant="outline"          size="sm"          className="mt-auto self-start"          onPress={() => {            setMessages([])            sendMessage(question)          }}        >          Replay        </Button>      )}    </div>  )}

Usage

A command is a collapsible line whose content is a code block with the output. The title says whether it is running, ran, or failed, and carries the exit code when it is not zero.

import { TerminalIcon } from "lucide-react"
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import {  TraceCollapsible,  TraceCollapsibleContent,  TraceCollapsibleTrigger,  TraceIcon,  TraceLine,  TraceTitle,} from "@/components/ui/trace"
<TraceCollapsible isExpanded={open ?? (running && output.length > 0)} onExpandedChange={setOpen}>  <TraceCollapsibleTrigger>    <TraceLine status={running ? "running" : failed ? "error" : undefined}>      <TraceIcon>        <TerminalIcon />      </TraceIcon>      <TraceTitle>{title}</TraceTitle>    </TraceLine>  </TraceCollapsibleTrigger>  <TraceCollapsibleContent>    <CodeBlock size="sm">      <CodeBlockContent wrap className="max-h-64">        {output}      </CodeBlockContent>    </CodeBlock>  </TraceCollapsibleContent></TraceCollapsible>

The block opens by itself while output arrives. Once the person opens or closes it, their choice stays.

Examples

Exit code

A command that exits with a non-zero code is in error. It opens by default, and the title says the code.

Ran pnpm install
> brevia-portal@0.1.0 lint
> eslint .

app/api/chat/route.ts
  14:7  error  'model' is assigned a value but never used  no-unused-vars

components/chat.tsx
  42:5  error  React Hook useEffect has a missing dependency: 'messages'  react-hooks/exhaustive-deps

✖ 2 problems (2 errors, 0 warnings)

 ELIFECYCLE  Command failed with exit code 1.

Long output

Cap the block with max-h-* so a command that prints hundreds of lines does not push the conversation away. The output scrolls inside the block.

imported order BM-3001
imported order BM-3002
imported order BM-3003
imported order BM-3004
imported order BM-3005
imported order BM-3006
imported order BM-3007
imported order BM-3008
imported order BM-3009
imported order BM-3010
imported order BM-3011
imported order BM-3012
imported order BM-3013
imported order BM-3014
imported order BM-3015
imported order BM-3016
imported order BM-3017
imported order BM-3018
imported order BM-3019
imported order BM-3020
imported order BM-3021
imported order BM-3022
imported order BM-3023
imported order BM-3024
imported order BM-3025
imported order BM-3026
imported order BM-3027
imported order BM-3028
imported order BM-3029
imported order BM-3030
imported order BM-3031
imported order BM-3032
imported order BM-3033
imported order BM-3034
imported order BM-3035
imported order BM-3036
imported order BM-3037
imported order BM-3038
imported order BM-3039
imported order BM-3040
imported order BM-3041
imported order BM-3042
imported order BM-3043
imported order BM-3044
imported order BM-3045
imported order BM-3046
imported order BM-3047
imported order BM-3048
imported order BM-3049
imported order BM-3050
imported order BM-3051
imported order BM-3052
imported order BM-3053
imported order BM-3054
imported order BM-3055
imported order BM-3056
imported order BM-3057
imported order BM-3058
imported order BM-3059
imported order BM-3060

AI SDK

The command is a runCommand tool whose output is the exit code. The text it prints is not the tool output: it streams alongside as a data part with the same id as the call, so the output can appear while the command is still running.

import type { UIMessage } from "ai"
type ChatMessage = UIMessage<  unknown,  { terminal: { output: string } },  {    runCommand: {      input: { command: string }      output: { exitCode: number }    }  }>

On the client, look up the data part that belongs to each call:

function getOutput(message: ChatMessage, toolCallId: string) {  for (const part of message.parts) {    if (part.type === "data-terminal" && part.id === toolCallId) {      return part.data.output    }  }
  return ""}

On the server, run the command from createUIMessageStream and write the accumulated output each time more arrives. Use the tool call id as the data part id:

writer.write({  type: "data-terminal",  id: toolCallId,  data: { output: accumulated },})

Write the whole output so far, not only the new chunk: writing a part with an existing id replaces it.

Scripted streams in development

createChat opens the call with a fixed toolCallId, streams the output line by line as data parts with that id, then resolves the call with an exit code:

const tool = writer.tool("runCommand", { toolCallId: id, input: { command } })
output.forEach((_, index) => {  writer    .data({ type: "data-terminal", id, data: { output: output.slice(0, index + 1).join("\n") } })    .sleep(200)})
tool.output({ exitCode: 0 })

Accessibility

KeyAction
EnterOpens or closes the output of the focused command.
SpaceOpens or closes the output of the focused command.
TabMoves focus to the next command, or into the output of an open command: the output block is focusable so it can be scrolled.

The composed components provide:

  • A trigger that is a real button with aria-expanded, and a panel tied to it.
  • A visible focus ring on the trigger.
  • A code block for the output, in monospace, with a height cap you set.

You provide:

  • The outcome in the title: "Ran pnpm lint", "pnpm lint exited with code 1", "Running pnpm build". The error colour is not the only signal, and the exit code is in the text.
  • Output that is safe to read. A terminal can print secrets and personal data. Filter them before they reach the stream.
  • A way to learn that a command finished. The output does not announce itself while it streams; say the result in the answer text.

Guidelines

When to use

  • When the output of a command is part of the answer, such as a build log or a lint report.
  • When the person needs the exit code to know whether the command worked.

When not to use

  • For a command whose output nobody needs. Use a Tool line and hide the output.
  • For a list of test results. Use Test Results.
  • For an error with a stack. Use Stack Trace.
  • For a terminal the person types into. This pattern is read-only.

Content

  • Write the command exactly as it ran, so the person can run it too.
  • Show the output unchanged, in order. Do not clean it up or trim the error at the end.
  • Cap the height and let it scroll. Open it by default only while it streams or when the command failed.
  • Say the exit code when it is not zero.
Do

Show the command as it ran and the exit code when it failed.

Don’t

Don’t summarise a failed command as "Build failed". The person needs the output to act on it.

Human in the loop

A command runs on a real machine, so the person sees it, can stop it and can refuse it.

  • Ask before a command that deletes, installs, deploys or touches anything outside the project, with Confirmation. Show the command in the question.
  • Show the command and its working directory before it runs, not after.
  • Let the person stop a command that is still running, with a stop control for the turn.
  • Keep the output in the transcript after it finishes. A command that ran without output still leaves its line and its exit code.

Composition

ComponentWhat it does here
TraceLays out the command line and the collapsible, and carries the running and error status.
Code BlockShows the output in monospace, with a height cap and wrapping.
MessagePlaces the conversation in turns.
BubbleWraps the person's own message.
ButtonThe replay control of the demo.

components/ai-elements/terminal.tsx exports TerminalDemo, a scripted chat that runs three commands and streams their output into data parts. Copy CommandRow, getTitle and getOutput into your app and replace the scripted chat with useChat against your route.