# Streaming Text

> A reply that appears as it's written, with a stop button.

Page: https://uicontext.com/docs/components/streaming-text

Group: Chat.

## When to use

A reply that appears as it's written, with a stop button. Use [Conversation](https://uicontext.com/docs/components/conversation.md) instead when you show whole messages with their actions.

## Usage

```ts
import { Stream, type StreamStatus } from "./ui/uicontext/components/Stream.ts"

const Message = UiSchema.TaggedEnum({ ClickedStopReply: {}, ClickedRetryReply: {} })

// your app appends each chunk to `text` as it arrives, and sets `status` when the reply ends
export const Reply = (h: Html.H<typeof Message.Type>, reply: { readonly status: StreamStatus; readonly text: string }) =>
	Stream(h, {
		key: "reply-1",
		status: reply.status,
		text: reply.text,
		onStop: Message.ClickedStopReply(),
		onRetry: Message.ClickedRetryReply(),
	})
```

## Examples

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

### A reply as it's written

Markdown renders as the words arrive, a half-written code block stays a code block, and Stop keeps what was written.

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

const REPLY = `The sign-in link expires after **10 minutes**, but the mail queue has taken up to 14 this week.

Raise the lifetime and keep the check that a link is used once:

\`\`\`ts
export const LINK_TTL = Duration.minutes(30)

export const isValid = (link: Link, now: Date) =>
  !link.used && now.getTime() - link.sentAt.getTime() < Duration.toMillis(LINK_TTL)
\`\`\`

Then add a test that delivers the email 20 minutes late and still signs in.`

// a few characters at a time, as a model's tokens arrive
const CHUNKS = REPLY.match(/[\s\S]{1,6}/gu) ?? []

const Message = UiSchema.TaggedEnum({
	ReceivedChunk: { index: Schema.Number },
	ClickedStop: {},
	ClickedRetry: {},
})

const Status = Schema.Literals(["waiting", "streaming", "succeeded", "stopped"])

// Stands in for the model's stream: one chunk every 40ms while the reply runs.
const tokens = (run: number) =>
	Subscription.make("reply-tokens", run, () =>
		EffectStream.fromIterable(CHUNKS.map((_, index) => index)).pipe(
			EffectStream.schedule(Schedule.spaced("40 millis")),
			EffectStream.map((index) => Message.ReceivedChunk({ index })),
		),
	)

const styles = stylex.create({
	frame: { display: "grid", gap: space.lg, inlineSize: "min(100%, 36rem)" },
})

export const StreamingReply = Html.component({
	name: "StreamingReply",
	model: Schema.Struct({ status: Status, received: Schema.Number, run: Schema.Number }),
	message: Message,
}).make({
	init: () => ({ status: "waiting" as const, received: 0, run: 1 }),
	subscriptions: ($) => ($.model.status === "waiting" || $.model.status === "streaming" ? [tokens($.model.run)] : []),
	update: {
		ReceivedChunk: ($, { index }) =>
			$.model.status === "stopped"
				? $.model
				: $.evolve({ received: index + 1, status: index + 1 >= CHUNKS.length ? "succeeded" : "streaming" }),
		ClickedStop: ($) => $.evolve({ status: "stopped" }),
		ClickedRetry: ($) => $.evolve({ status: "waiting", received: 0, run: (n) => n + 1 }),
	},
	view: (h, model) =>
		h.div.attrs(sx(styles.frame)).children(
			Stream(h, {
				key: "stream-demo",
				status: model.status,
				text: CHUNKS.slice(0, model.received).join(""),
				reasoning: { seconds: 4, text: "Compare the link lifetime with how long the queue takes to deliver." },
				onStop: Message.ClickedStop(),
				onRetry: Message.ClickedRetry(),
			}),
			model.status === "succeeded" &&
				Button(h, { emphasis: "ghost", size: "sm" }).on("click", Message.ClickedRetry()).children("Play again"),
		),
})
```

### Waiting and how a reply ends

Before the first word it says it's thinking; at the end it says whether the reply finished, who stopped it, or why it failed.

```ts title="src/endings.ts" source="www/src/examples/streaming-text/endings.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import type { Actor } from "./ui/uicontext/components/domain/Actor.ts"
import { Stream } from "./ui/uicontext/components/Stream.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"

const grace: Actor = { id: "grace", name: "Grace Hopper", kind: "person" }

const styles = stylex.create({
	list: { display: "grid", gap: space.xl, inlineSize: "min(100%, 36rem)" },
	label: { margin: 0, marginBlockEnd: space.xs, fontSize: font.xs, color: color.faint },
})

// a labelled case; the caller adds the reply as its next child
const Case = <M>(h: Html.H<M>, label: string) => h.div.children(h.p.attrs(sx(styles.label)).children(label))

export const ReplyEndings = <M>(h: Html.H<M>) =>
	h.div.attrs(sx(styles.list)).children(
		Case(h, "Waiting").children(Stream(h, { key: "end-waiting", status: "waiting", text: "", waitingLabel: "Reading 14 files…" })),
		Case(h, "Finished").children(
			Stream(h, {
				key: "end-done",
				status: "succeeded",
				text: "All 212 tests pass. The flaky `checkout.spec.ts` now waits for the payment frame instead of sleeping.",
				reasoning: { seconds: 38, text: "Run the suite three times and compare which tests fail." },
			}),
		),
		Case(h, "Stopped by a person").children(
			Stream(h, {
				key: "end-stopped",
				status: "stopped",
				stoppedBy: grace,
				text: "I'll start by renaming every `customerId` column to",
			}),
		),
		Case(h, "Failed").children(
			Stream(h, {
				key: "end-failed",
				status: "failed",
				failure: "The model took too long to answer. Nothing was changed.",
				text: "",
			}),
		),
	)
```

## API reference

### CodeBlockView (component)

**Props**

| Name | Type | Description |
| --- | --- | --- |
| `code` (required) | `string` | — |
| `language` | `string` | — |
| `runLabel` | `string` | The run button's label ("Run", "Preview"); no button when left out |
| `streaming` | `boolean` | Still being written: no fold, and no run until it's whole |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedRun` | `{ code: string; language: string \| null }` | The person pressed the block's run button (`runLabel`): run or preview `code` |

### CodeBlock (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `key` (required) | `string` | Tells several on one page apart |
| `code` (required) | `string` | — |
| `language` | `string` | — |
| `streaming` | `boolean` | Still being written |
| `run` | `{ readonly label: string; readonly message: Message }` | A Run or Preview button for this code: its label, and the message it sends |

### Reasoning (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `thinking` | `boolean` | Still thinking: the shimmering label instead of the disclosure |
| `seconds` | `number` | How long it thought, once done |
| `text` | `string` | The reasoning itself, shown when the disclosure opens; untrusted model text |

### Stream (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `status` (required) | `"waiting" \| "streaming" \| "succeeded" \| "stopped" \| "failed"` | Waiting for the first words, streaming, or ended: succeeded, stopped or failed |
| `text` (required) | `string` | Everything received so far |
| `waitingLabel` | `string` | Shown while nothing has arrived yet; "Thinking…" when left out |
| `reasoning` | `{ readonly text?: string \| undefined; readonly seconds?: number \| undefined }` | The agent's reasoning: shown as "Thought for Ns" above the reply once text arrives |
| `stoppedBy` | `Actor` | For "stopped": who stopped it |
| `failure` | `string` | For "failed": why, in a sentence |
| `onStop` | `Message` | Send to stop it; omit when this person can't stop it |
| `onRetry` | `Message` | Send to try again once it failed or was stopped; omit when it can't be retried |
| `key` | `string` | Tells this reply's code blocks apart from other replies' on the page: the message id |

### ReplyView (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `streaming` | `boolean` | The text is still arriving: code blocks stay unfolded |
| `run` | `((code: string, language: string \| undefined) => { readonly label: string; readonly message: Message } \| undefined)` | A Run or Preview button for code the app can run: its label and message, or undefined for none |

## Keyboard and accessibility

- Screen readers hear the end state, not every word: the footer is a status that says Writing, then done, stopped (and by whom) or failed (and why).
- The message is marked busy while it runs, and Stop is a real button.
- The agent's reasoning folds into a `<details>` that opens with Enter or Space.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/streaming-text
```

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

It writes these files:

- `src/ui/uicontext/components/Button.ts`
- `src/ui/uicontext/components/CopyButton.ts`
- `src/ui/uicontext/components/IconStroke.ts`
- `src/ui/uicontext/components/Prose.ts`
- `src/ui/uicontext/components/Stream.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/button.stylex.ts`
- `src/ui/uicontext/components/domain/Actor.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/variants.ts`

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

## Source

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

## Used in

- [Work](https://uicontext.com/blocks/work.md)
- [Bots](https://uicontext.com/blocks/bot-console.md)

## Related

- [Conversation](https://uicontext.com/docs/components/conversation.md) (`conversation`): What a person and an assistant say to each other, with actions, sources and tool calls on each message.
- [Composer](https://uicontext.com/docs/components/composer.md) (`composer`): Write and send a message, with attachments and modes.
- [Conversation Viewport](https://uicontext.com/docs/components/conversation-viewport.md) (`conversation-viewport`): Keeps the newest message in view, and lets you scroll back without losing your place.
- [Agent Plan](https://uicontext.com/docs/components/agent-plan.md) (`agent-plan`): What an agent did and plans to do, step by step, with each step's input and result.
- [Tool Call](https://uicontext.com/docs/components/tool-call.md) (`tool-call`): What an assistant's tools did, one past-tense row each, such as "Searched the web · 8 sources". Each opens to what it read.
- [Approval](https://uicontext.com/docs/components/approval.md) (`approval`): Asks a person to allow an action before an agent takes it.
