# Terminal

> The panes of a coding agent's workspace: files, a terminal and an editor.

Page: https://uicontext.com/docs/components/terminal

Group: Agents.

## When to use

The panes of a coding agent's workspace: files, a terminal and an editor. Use [Computer](https://uicontext.com/docs/components/computer.md) instead when the agent works in a browser or on a desktop.

## Usage

```ts
import { Terminal, type TerminalEntry } from "./ui/uicontext/components/Shell.ts"

export const AgentTerminal = <M>(h: Html.H<M>, entries: ReadonlyArray<TerminalEntry>, running: boolean) =>
	Terminal(h, { label: "Terminal", entries, streaming: running })
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### A test run, as it streams

The agent's commands with their output in its own colors. Lines arrive as they're written, a progress bar redraws in place, and each command copies with its output.

```ts title="src/demo.ts" source="www/src/examples/terminal/demo.ts"
import { Subscription, UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schedule, Schema, Stream } from "effect"
import { Button } from "./ui/uicontext/components/Button.ts"
import { Terminal, type TerminalEntry } from "./ui/uicontext/components/Shell.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { space } from "./ui/uicontext/components/tokens.stylex.ts"

const ESC = "\u001b"
const green = (s: string) => `${ESC}[32m${s}${ESC}[0m`
const red = (s: string) => `${ESC}[31m${s}${ESC}[0m`
const dim = (s: string) => `${ESC}[2m${s}${ESC}[0m`
const bold = (s: string) => `${ESC}[1m${s}${ESC}[0m`

const done: ReadonlyArray<TerminalEntry> = [
	{
		id: "install",
		command: "bun install",
		cwd: "~/billing",
		output: [{ text: `${dim("bun install v1.4.2")}\n\n${green("✓")} 367 packages installed ${dim("[412ms]")}` }],
		exitCode: 0,
	},
	{
		id: "lint",
		command: "bun run lint",
		cwd: "~/billing",
		output: [
			{ text: `${bold("src/invoice/tax.ts")}\n  14:7  ${ESC}[33mwarning${ESC}[0m  'rate' is assigned but never used  no-unused-vars` },
			{ text: `\n${ESC}[33m✖ 1 problem (0 errors, 1 warning)${ESC}[0m` },
		],
		exitCode: 0,
	},
]

// the test run's lines, in the order the runner writes them
const LINES: ReadonlyArray<{ readonly text: string; readonly error?: boolean }> = [
	{ text: dim("bun test v1.4.2") },
	{ text: `\nsrc/invoice/total.test.ts:\n${green("✓")} sums line items ${dim("[0.4ms]")}` },
	{ text: `\n${green("✓")} rounds once on the total ${dim("[0.2ms]")}` },
	{ text: `\n${red("✗")} adds VAT once for EU customers ${dim("[1.1ms]")}`, error: true },
	{ text: `\n  ${red("expect(received).toBe(expected)")}\n  Expected: ${green("120.00")}\n  Received: ${red("144.00")}`, error: true },
	{ text: `\n\nsrc/invoice/pdf.test.ts:\nRendering 40 invoices ${"█".repeat(4)}${"░".repeat(16)} 20%\rRendering 40 invoices ${"█".repeat(12)}${"░".repeat(8)} 60%\rRendering 40 invoices ${"█".repeat(20)} 100%` },
	{ text: `\n${green("✓")} renders every invoice ${dim("[812ms]")}` },
	{ text: `\n\n ${green("211 pass")}\n ${red("1 fail")}\n Ran 212 tests across 18 files. ${dim("[1.94s]")}` },
]

const Message = UiSchema.TaggedEnum({ ReceivedLine: { count: Schema.Number }, ClickedRunAgain: {} })

// Stands in for the shell's output stream: a line every 350ms.
const lines = (run: number) =>
	Subscription.make("test-lines", run, () =>
		Stream.fromIterable(LINES.map((_, i) => i + 1)).pipe(
			Stream.schedule(Schedule.spaced("350 millis")),
			Stream.map((count) => Message.ReceivedLine({ count })),
		),
	)

const styles = stylex.create({
	frame: { display: "grid", gridTemplateRows: "minmax(0, 1fr) auto", gap: space.md, inlineSize: "100%", blockSize: 360 },
})

export const TestRun = Html.component({
	name: "TestRun",
	model: Schema.Struct({ received: Schema.Number, run: Schema.Number }),
	message: Message,
}).make({
	init: () => ({ received: 0, run: 1 }),
	subscriptions: ($) => ($.model.received < LINES.length ? [lines($.model.run)] : []),
	update: {
		ReceivedLine: ($, { count }) => $.evolve({ received: count }),
		ClickedRunAgain: ($) => $.evolve({ received: 0, run: (n) => n + 1 }),
	},
	view: (h, model) => {
		const running = model.received < LINES.length
		return h.div.attrs(sx(styles.frame)).children(
			Terminal(h, {
				label: "Terminal",
				streaming: running,
				entries: [
					...done,
					{ id: `test-${model.run}`, command: "bun test src/invoice", cwd: "~/billing", output: LINES.slice(0, model.received), exitCode: running ? null : 1 },
				],
			}),
			!running && Button(h, { size: "sm" }).on("click", Message.ClickedRunAgain()).children("Run the tests again"),
		)
	},
})
```

### Before anything runs

While the session starts the terminal shows a placeholder; with nothing run yet it says so and what comes next.

```ts title="src/states.ts" source="www/src/examples/terminal/states.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Terminal } from "./ui/uicontext/components/Shell.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	grid: { display: "grid", gap: space.lg, gridTemplateColumns: "repeat(auto-fit, minmax(16rem, 1fr))", inlineSize: "100%" },
	pane: { display: "grid", gap: space.xs, blockSize: 200, alignContent: "start" },
	label: { margin: 0, fontSize: font.xs, color: color.faint },
})

export const TerminalStates = <M>(h: Html.H<M>) =>
	h.div.attrs(sx(styles.grid)).children(
		h.div.attrs(sx(styles.pane)).children(
			h.p.attrs(sx(styles.label)).children("Starting"),
			Terminal(h, { label: "Terminal", entries: [], status: "loading" }),
		),
		h.div.attrs(sx(styles.pane)).children(
			h.p.attrs(sx(styles.label)).children("Nothing run yet"),
			Terminal(h, {
				label: "Terminal",
				entries: [],
				empty: { title: "Nothing has run yet", hint: "Commands the agent runs show here with their output." },
			}),
		),
	)
```

## API reference

### FileTree (component)

**Props**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `id` (required) | `string` | — | Identifies the tree for agents |
| `label` (required) | `string` | — | The tree's accessible name: "Files" |
| `nodes` (required) | `FileNode[]` | — | The files and folders at the top level, each folder with its children |
| `status` | `"loading" \| "ready"` | `"ready"` | "loading" shows a placeholder; "ready" by default |
| `selected` | `string \| null` | — | The open file |
| `defaultOpen` | `string[]` | — | Folders open at first; default the top level |
| `agentId` | `string` | — | The id agents see this tree by; `files:<id>` when left out |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedOpenFile` | `{ path: string }` | The person picked a file to open |

**Agent actions**

| Action | Description |
| --- | --- |
| `ToggledFolder` | Open or close a folder by its path |
| `ClickedFile` | Open a file by its path |

### FileEditor (component)

**Props**

| Name | Type | Description |
| --- | --- | --- |
| `id` (required) | `string` | Identifies the editor in the events it sends |
| `path` (required) | `string` | The file's path, shown as the editor's heading |
| `value` (required) | `string` | The file's saved text; the person's edits stay a draft until Save |
| `language` | `string` | "TypeScript", shown in the status bar |
| `readOnly` | `string` | Why it can't be edited: "The agent is working in this file" |
| `saveLabel` | `string` | "Save", "Save draft"; leave `can` without "save" to hide it |
| `can` (required) | `"save"[]` | "save" when this person may save; read-only without it |
| `outcome` | `Outcome \| null` | The app's answer to the request in flight; its request is the action's id |
| `agentId` | `string` | The id agents see this editor by; `file:<id>` when left out |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedSave` | `{ id: string; path: string; value: string }` | The person saved their draft |

**Agent actions**

| Action | Description |
| --- | --- |
| `UpdatedText` | Replace the file's whole text (saved with SubmittedSave) |
| `SubmittedSave` | Save the edited file |
| `ClickedDiscard` | Throw away unsaved edits |

### Terminal (view function)

**Options**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` | — | The log's accessible name: "Terminal" |
| `entries` (required) | `TerminalEntry[]` | — | The commands and their output, oldest first |
| `status` | `"loading" \| "ready"` | `"ready"` | "loading" shows a placeholder; "ready" by default |
| `empty` | `{ readonly title: string; readonly hint?: string }` | — | What shows before anything has run; "Nothing has run yet" when left out |
| `streaming` | `boolean` | — | Lines are still arriving |
| `maxLines` | `number` | `400` | Lines of one command's output shown before the rest fold away; 400 by default |
| `copy` | `boolean` | `true` | A Copy button on each command, for its prompt and output; true by default |

### PaneSwitcher (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `label` (required) | `string` | The group's accessible name: "Workspace panes" |
| `panes` (required) | `ReadonlyArray<{ readonly id: string; readonly label: string; readonly badge?: string }>` | The panes to pick from, each with an optional badge: "3" |
| `current` (required) | `string` | The id of the pane showing |
| `onCurrentChange` (required) | `(id: string) => Message` | The message for picking a pane |

## Keyboard and accessibility

- The file tree is a `nav`: folders open and close as disclosures, and the open file is marked `aria-current`.
- The terminal is a focusable `log`, so new lines are announced and the keyboard can scroll it.
- The editor is a labelled text area; Mod+S saves. The pane switcher is a row of toggle buttons (`aria-pressed`).

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/terminal
```

With npm: `npx shadcn@latest add checkfu/uicontext/terminal`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/terminal`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/terminal`.

It writes these files:

- `src/ui/uicontext/components/Button.ts`
- `src/ui/uicontext/components/Callout.ts`
- `src/ui/uicontext/components/CopyButton.ts`
- `src/ui/uicontext/components/IconStroke.ts`
- `src/ui/uicontext/components/Shell.ts`
- `src/ui/uicontext/components/Skeleton.ts`
- `src/ui/uicontext/components/States.ts`
- `src/ui/uicontext/components/StatusBadge.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/agent/Agent.ts`
- `src/ui/uicontext/components/button.stylex.ts`
- `src/ui/uicontext/components/domain/Format.ts`
- `src/ui/uicontext/components/domain/Outcome.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/variants.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/Shell.ts](https://github.com/checkfu/uicontext/blob/main/src/Shell.ts)

## Used in

- [Agent studio](https://uicontext.com/blocks/agent-studio.md)

## Related

- [Agent Tools](https://uicontext.com/docs/components/agent-tools.md) (`agent-tools`): Lets agents in the browser read the page and act through the same controls people use.
- [Tool Confirmation](https://uicontext.com/docs/components/tool-confirmation.md) (`tool-confirmation`): Asks a person to confirm before an agent's action changes anything.
- [Prompt Template](https://uicontext.com/docs/components/prompt-template.md) (`prompt-template`): Write a prompt with {{variables}} the app fills in: they stand out, unknown ones are flagged, and a preview shows it with samples.
- [Agent Settings](https://uicontext.com/docs/components/agent-settings.md) (`agent-settings`): Edit an agent's name, instructions, tools and model.
- [Computer](https://uicontext.com/docs/components/computer.md) (`computer`): The machine an agent works on: a live view of its screen, full size or as a thumbnail with Take over, and its browser with tabs and an address bar.
- [Persona Avatar](https://uicontext.com/docs/components/persona-avatar.md) (`persona-avatar`): An agent's face: a shape and a color with eyes that move with what it's doing.
