Script a conversation in a streaming server action and render it through the kit's message scroller, with no model, no hand-written endpoint, and no API key.
Write an AI conversation in code and stream it to the page, with no model, API route, network request, or API key. WebJs needs no helper package for this: a 'use server' action that is an async generator already streams its results over one response. So the script lives in an action that yields message parts, and a component appends each part as it arrives.
// modules/chat/actions/reply.server.ts
'use server';
import type { Message, Part } from '#modules/chat/types.ts';
const replies = [
'The release adds keyboard shortcuts and faster search.',
'Press ⌘K to search and ⌘Enter to submit.',
];
export async function* reply(messages: Message[]): AsyncGenerator<Part> {
const turn = messages.filter((m) => m.role === 'user').length - 1;
yield { id: 'text', type: 'text', text: replies[turn] };
}
The component sends the transcript and folds each part into the assistant message it is building. The parts arrive as the action yields them, so your components behave as they would with a real model.
const assistant: Message = { id: crypto.randomUUID(), role: 'assistant', parts: [] };
this.messages.set([...transcript, assistant]);
for await (const part of await reply(transcript)) {
this.update(assistant.id, part);
}
The action receives the whole transcript, so it can pick the reply that follows it. Text, reasoning, tool calls, data, files and sources are all just parts, and a tool call can pause for the person. See Human in the Loop.
What It's For
The script decouples your chat UI from the model, so you can work on the frontend on its own. It needs no model and no API key, and it streams the same way every time.
- Build components. Develop message bubbles, tool cards, and reasoning panels against realistic streaming output, without wiring up a model first.
- Preview and demo. Ship reproducible previews, screenshots, and videos that never depend on a live model.
- Write docs. Power documentation examples with conversations that render the same way on every load.
- Test. On the server the action is a plain async generator, so a test can call it directly and assert on what it yields, with no network calls, token spend, or flaky model output.
Installation
WebJs streams an action's results on its own, so the helper is three files you write: the message types, the scripted action, and the chat component, all shown below. The thread renders with the kit's components:
To answer from a real model, the same action can call the AI SDK's streamText (from the ai package) on the server and yield parts as its stream produces them. No client package is needed, since the component is a WebComponent. See the AI SDK docs for the stream it returns.
Usage
List the scripted questions where the component can read them, script the replies in the action, then send each question from the component.
// modules/chat/script.ts (browser-safe: the component reads it)
export const questions = [
'What changed in this release?',
'Can you show me the shortcuts?',
];
// modules/chat/actions/reply.server.ts
'use server';
import type { Message, Part } from '#modules/chat/types.ts';
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
// One part, a word at a time: each chunk is the part so far, under one id.
async function* words(id: string, type: 'text' | 'reasoning', text: string, delayMs = 50): AsyncGenerator<Part> {
let sent = '';
for (const word of text.split(/(?<= )/)) {
sent += word;
yield { id, type, text: sent };
await sleep(delayMs);
}
}
const turns = [
async function* () {
yield* words('text', 'text', 'The release adds keyboard shortcuts and faster search.');
},
async function* () {
yield* words('text', 'text', 'Press ⌘K to search and ⌘Enter to submit.');
},
];
export async function* reply(messages: Message[]): AsyncGenerator<Part> {
const turn = turns[messages.filter((m) => m.role === 'user').length - 1];
if (!turn) {
yield { id: 'text', type: 'text', text: 'This demo has no more predefined replies.' };
return;
}
yield* turn();
}
// modules/chat/components/scripted-chat.ts
import { WebComponent, signal, html } from '@webjsdev/core';
import { reply } from '#modules/chat/actions/reply.server.ts';
import { questions } from '#modules/chat/script.ts';
import type { Message, Part } from '#modules/chat/types.ts';
// A part whose id the message already holds replaces it; a new id appends.
const upsert = (parts: Part[], part: Part) =>
parts.some((p) => p.id === part.id)
? parts.map((p) => (p.id === part.id ? part : p))
: [...parts, part];
// renderPart(part) draws one part with the kit's helpers (see Message Parts).
export class ScriptedChat extends WebComponent {
private messages = signal<Message[]>([]);
private busy = signal(false);
private nextQuestion() {
return questions[this.messages.get().filter((m) => m.role === 'user').length];
}
private update(id: string, part: Part) {
this.messages.set(this.messages.get().map((m) =>
m.id === id ? { ...m, parts: upsert(m.parts, part) } : m));
}
private async stream(id: string, transcript: Message[]) {
this.busy.set(true);
try {
for await (const part of await reply(transcript)) this.update(id, part);
} finally {
this.busy.set(false);
}
}
private async send() {
const text = this.nextQuestion();
if (!text || this.busy.get()) return;
const user: Message = { id: crypto.randomUUID(), role: 'user', parts: [{ id: 'text', type: 'text', text }] };
const transcript = [...this.messages.get(), user];
const id = crypto.randomUUID();
this.messages.set([...transcript, { id, role: 'assistant', parts: [] }]);
await this.stream(id, transcript);
}
render() {
return html`
<ui-message-scroller auto-scroll class="h-96">
<ui-message-scroller-viewport>
<ui-message-scroller-content aria-label="Conversation">
${this.messages.get().map((m) => html`
<ui-message-scroller-item message-id=${m.id} ?scroll-anchor=${m.role === 'user'}>
${m.parts.map(renderPart)}
</ui-message-scroller-item>`)}
</ui-message-scroller-content>
</ui-message-scroller-viewport>
<ui-message-scroller-button></ui-message-scroller-button>
</ui-message-scroller>
<button ?disabled=${!this.nextQuestion() || this.busy.get()} @click=${() => this.send()}>Send</button>
`;
}
}
ScriptedChat.register('scripted-chat');
Reset
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
cardClass, cardHeaderClass, cardTitleClass, cardDescriptionClass,
cardActionClass, cardContentClass, cardFooterClass,
} from '#components/ui/card.ts';
import {
inputGroupClass, inputGroupAddonClass, inputGroupButtonClass, inputGroupTextareaClass,
} from '#components/ui/input-group.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
import {
ArrowUpIcon, BrainIcon, GlobeIcon, ImageIcon, PaperclipIcon, PlusIcon,
RotateCwIcon, TelescopeIcon,
} from '#lib/ui/lucide.ts';
type Part = { type: 'reasoning' | 'text'; paragraphs: unknown[] };
type ChatMessage = { id: string; role: 'user' | 'assistant'; parts: Part[] };
const code = (text: string) => html`<code class="rounded-md bg-muted px-1 py-0.5 font-mono text-[0.85em]">${text}</code>`;
const text = (...paragraphs: unknown[]): Part => ({ type: 'text', paragraphs });
// shadcn's scripted conversation, once every turn has been sent. In a real
// chat these messages are what a streaming 'use server' action yielded (see
// the AI SDK helper page). The replies name the scroller's API, which on this
// site is the kit's element and attributes.
const messages: ChatMessage[] = [
{
id: 'user-1',
role: 'user',
parts: [text("I'm building a chat for our app and the scroll behavior is driving me nuts. Every time the AI streams a reply, the whole thread jumps around.")],
},
{
id: 'assistant-1',
role: 'assistant',
parts: [
{ type: 'reasoning', paragraphs: ['They are describing a streaming transcript that keeps taking control of the viewport. I should explain when auto-scroll follows and when it stops.'] },
text(
html`That's the classic streaming scroll problem. Wrap your message list in ${code('ui-message-scroller')} and turn on ${code('auto-scroll')}. The viewport pins to the bottom as tokens arrive, so users always see the latest text land in place.`,
"The important part: it only auto-scrolls while the reader is already at the bottom. The moment they scroll up to read something earlier, auto-scroll backs off and their position is preserved. You get smooth streaming without fighting the user's intent.",
),
],
},
{
id: 'user-2',
role: 'user',
parts: [text('Okay, but when someone sends a new message the view still feels jarring, like the whole conversation reloads from the top.')],
},
{
id: 'assistant-2',
role: 'assistant',
parts: [text(
html`${code('ui-message-scroller-item')} fixes that with turn anchoring. Set ${code('scroll-anchor')} on the turn that should settle near the top instead of blindly snapping to the document bottom.`,
"It also leaves a small peek of the previous exchange visible above the anchor, so context isn't lost. The reply starts in view without that disorienting jump you get from a plain overflow container.",
)],
},
{
id: 'user-3',
role: 'user',
parts: [text("And if they've scrolled up to re-read an older answer? I don't want to yank them back down.")],
},
{
id: 'assistant-3',
role: 'assistant',
parts: [text(
"You won't. Auto-scroll only runs when the viewport is already pinned to the bottom, so scrolling up is a deliberate opt-out. Their place in the thread stays put even as new tokens keep arriving below.",
html`When there is content they haven't seen yet, ${code('ui-message-scroller-button')} appears at the bottom of the viewport. One tap jumps them back to the newest message and re-engages auto-scroll. Same pattern as Slack or iMessage: quiet when you're caught up, helpful when you're not.`,
)],
},
{
id: 'user-4',
role: 'user',
parts: [text('Last one: does this work with assistive tech?')],
},
{
id: 'assistant-4',
role: 'assistant',
parts: [text(
html`${code('ui-message-scroller-content')} sets ${code('role="log"')} and ${code('aria-relevant="additions"')} by default, so screen readers announce new messages as they stream in.`,
html`The scroll button is a real ${code('<button>')} with an sr-only label, and it's removed from the tab order when you're already at the bottom, so there are no ghost focus stops.`,
)],
},
];
function part(p: Part, user: boolean) {
if (p.type === 'reasoning') {
return html`
<div class="w-full border-l-2 border-muted-foreground/30 pl-3 text-muted-foreground">
<div class="mb-1 flex items-center gap-1.5 text-xs font-medium">${BrainIcon('size-3.5')}Reasoning</div>
<div class="space-y-1.5 text-sm">${p.paragraphs.map((t) => html`<p class="whitespace-pre-wrap">${t}</p>`)}</div>
</div>`;
}
const variant = user ? 'muted' : 'ghost';
return html`
<div data-slot="bubble" data-variant=${variant} class=${bubbleClass({ variant })}>
<div data-slot="bubble-content" class=${cn(bubbleContentClass(), 'space-y-2')}>
${p.paragraphs.map((t) => html`<p class="whitespace-pre-wrap">${t}</p>`)}
</div>
</div>`;
}
const row = (m: ChatMessage) => {
const user = m.role === 'user';
return html`
<ui-message-scroller-item message-id=${m.id} ?scroll-anchor=${user}>
<div data-slot="message" data-align=${user ? 'end' : 'start'} class=${messageClass()}>
<div data-slot="message-content" class=${messageContentClass()}>
${m.parts.map((p) => part(p, user))}
</div>
</div>
</ui-message-scroller-item>`;
};
// Sending and Reset are the reader's to wire: the AI SDK helper page streams
// each reply from a 'use server' action into a component like this one.
export default function AiSdkHelperDemo() {
return html`
<div class="relative flex flex-col gap-4">
<div data-slot="card" data-size="default" class=${cn(cardClass(), 'mx-auto h-140 w-full max-w-sm gap-0')}>
<div data-slot="card-header" class=${cn(cardHeaderClass(), 'gap-1 border-b')}>
<div data-slot="card-title" class=${cardTitleClass()}>New Chat</div>
<div data-slot="card-description" class=${cardDescriptionClass()}>How can I help you today?</div>
<div data-slot="card-action" class=${cardActionClass()}>
<ui-tooltip>
<ui-tooltip-trigger>
<button type="button" data-slot="button" data-variant="outline" data-size="icon" aria-label="Reset conversation" class=${buttonClass({ variant: 'outline', size: 'icon' })}>${RotateCwIcon()}</button>
</ui-tooltip-trigger>
<ui-tooltip-content><p>Reset</p></ui-tooltip-content>
</ui-tooltip>
</div>
</div>
<div data-slot="card-content" class=${cn(cardContentClass(), 'flex-1 overflow-hidden p-0')}>
<ui-message-scroller>
<ui-message-scroller-viewport>
<ui-message-scroller-content aria-label="Conversation" class="p-(--card-spacing)">
${messages.map(row)}
</ui-message-scroller-content>
</ui-message-scroller-viewport>
<ui-message-scroller-button></ui-message-scroller-button>
</ui-message-scroller>
</div>
<div data-slot="card-footer" class=${cn(cardFooterClass(), 'flex-col gap-2')}>
<form class="w-full">
<div data-slot="input-group" role="group" class=${inputGroupClass()}>
<textarea data-slot="input-group-control" aria-label="Next predefined message" data-status="ready" placeholder="No messages queued. Reset the conversation." readonly class=${cn(inputGroupTextareaClass(), 'h-14 min-h-14 overflow-hidden px-3 py-2.5 opacity-60 data-[status=ready]:opacity-100')}></textarea>
<div role="group" data-slot="input-group-addon" data-align="block-end" class=${cn(inputGroupAddonClass({ align: 'block-end' }), 'pt-1')}>
<ui-dropdown-menu>
<ui-dropdown-menu-trigger>
<button type="button" aria-label="Add files" data-slot="button" data-variant="outline" data-size="icon-sm" class=${inputGroupButtonClass({ variant: 'outline', size: 'icon-sm' })}>${PlusIcon()}</button>
</ui-dropdown-menu-trigger>
<ui-dropdown-menu-content align="start" side="top" class="w-44">
<ui-dropdown-menu-item>${PaperclipIcon()}Add Photos & Files</ui-dropdown-menu-item>
<ui-dropdown-menu-separator></ui-dropdown-menu-separator>
<ui-dropdown-menu-item>${ImageIcon()}Create Image</ui-dropdown-menu-item>
<ui-dropdown-menu-item>${TelescopeIcon()}Deep Research</ui-dropdown-menu-item>
<ui-dropdown-menu-item>${GlobeIcon()}Web Search</ui-dropdown-menu-item>
</ui-dropdown-menu-content>
</ui-dropdown-menu>
<button type="submit" disabled data-slot="button" data-variant="default" data-size="icon-sm" class=${cn(inputGroupButtonClass({ variant: 'default', size: 'icon-sm' }), 'ml-auto')}>
${ArrowUpIcon()}<span class="sr-only">Send</span>
</button>
</div>
</div>
</form>
</div>
</div>
<div class="px-0.5 text-center text-xs text-muted-foreground">
Demo is read only. Press send to send messages.
</div>
</div>
`;
}
View Code
User Messages
Messages use the user and assistant roles. The component builds the person's message itself, as the next scripted question, before it calls the action.
const user: Message = {
id: crypto.randomUUID(),
role: 'user',
parts: [{ id: 'text', type: 'text', text: 'What changed in this release?' }],
};
The id is yours to choose, and any other field you need goes on the Message type. See Metadata and IDs.
User messages can also carry files. See Files.
Assistant Messages
The component adds an empty assistant message, then fills it with what the action yields. A reply that is one string is one text part.
yield { id: 'text', type: 'text', text: 'The release adds keyboard shortcuts and faster search.' };
Yield several parts, under different ids, when the message has more than plain text.
yield* words('thinking', 'reasoning', 'I should summarize the release.');
yield* words('text', 'text', 'The release adds keyboard shortcuts and faster search.');
The parts land in the order the action yields them.
Message Parts
An assistant message can hold many kinds of part, in the order the action yields them: Text and Reasoning, Tool Calls, Data, Files and Sources. The part type is yours, so it holds exactly what your UI renders.
// modules/chat/types.ts
export type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
export type ToolState =
| 'input-available' | 'approval-requested'
| 'output-available' | 'output-error' | 'output-denied';
export type Part =
| { id: string; type: 'text'; text: string }
| { id: string; type: 'reasoning'; text: string }
| { id: string; type: 'tool'; name: string; state: ToolState; input: Json; output?: Json; errorText?: string; approved?: boolean }
| { id: string; type: 'data'; name: string; data: Json }
| { id: string; type: 'file'; filename: string; mediaType: string; url: string }
| { id: string; type: 'source'; title: string; url: string };
export interface Message {
id: string;
role: 'user' | 'assistant';
parts: Part[];
}
The component renders each part with the kit's helpers: a Bubble for text, a Trace line for a tool call.
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { traceClass, traceLineClass, traceTitleClass } from '#components/ui/trace.ts';
function renderPart(part: Part) {
switch (part.type) {
case 'text':
return html`<div data-slot="bubble" class=${bubbleClass()}>
<div data-slot="bubble-content" class=${bubbleContentClass()}>${part.text}</div>
</div>`;
case 'reasoning':
return html`<p class="text-sm text-muted-foreground">${part.text}</p>`;
case 'tool':
return html`<div data-slot="trace" class=${traceClass()}>
<div data-slot="trace-line" class=${traceLineClass()}>
<span data-slot="trace-title" class=${traceTitleClass()}>${part.name}: ${part.state}</span>
</div>
</div>`;
default:
return '';
}
}
Text
Yield a text part. The words() helper in the action streams it a word at a time, yielding the part so far under one id, so the component replaces it in place on each chunk.
yield* words('text', 'text', 'The release adds keyboard shortcuts.');
yield* words('more', 'text', 'Search is faster too.');
Each id makes a separate part. To send a whole part at once, yield it once. To change the pace, pass a delay.
yield { id: 'done', type: 'text', text: 'Done.' };
yield* words('slow', 'text', 'This part streams more slowly.', 100);
Reasoning
Yield a reasoning part.
yield* words('thinking', 'reasoning', 'I should check the latest conditions first.');
yield* words('text', 'text', 'Let me check the weather.');
Reasoning streams the same way as text. Render it as a Reasoning trace, or in a muted block as the demo above does.
Tool Calls
Yield a tool part with its input, then yield it again under the same id once it has a result. The component replaces it, so the card moves from input to output.
const call = { id: 'weather', type: 'tool', name: 'getWeather', input: { city: 'San Francisco' } } as const;
yield { ...call, state: 'input-available' };
await sleep(900);
yield { ...call, state: 'output-available', output: { city: 'San Francisco', temperature: 18, condition: 'Breezy' } };
yield* words('text', 'text', 'It is 18°C and breezy in San Francisco.');
The call can finish with an output, an error, or a denial.
yield { ...call, state: 'output-error', errorText: 'The weather service is down.' };
yield { ...call, state: 'output-denied' };
To type each tool's input and output, make the tool member of Part a union with one member per tool name, and narrow on name where you render it.
type WeatherCall = {
id: string; type: 'tool'; name: 'getWeather'; state: ToolState;
input: { city: string };
output?: { city: string; temperature: number; condition: string };
};
A tool call can also wait for the person instead of finishing in the script. See Human in the Loop.
Human in the Loop
A tool call can pause and hand control to the person. Both flows work the same way: the action yields a tool part and returns, the component renders a control for it, and the person's answer goes back to the action in the next transcript.
Pause a Tool Call
Yield a tool part in the input-available state and end the generator. The reply finishes, and the part waits until the component supplies its output.
yield* words('text', 'text', "Answer these and I'll tailor the prototype.");
yield { id: 'ask', type: 'tool', name: 'askQuestions', state: 'input-available', input: { questions } };
Require Approval
Yield the part in the approval-requested state to pause behind the person's decision.
yield* words('text', 'text', 'That will archive 3 drafts. I need your approval.');
yield { id: 'archive', type: 'tool', name: 'archiveDrafts', state: 'approval-requested', input: { count: 3 } };
Continuations
When the transcript the action receives ends with an assistant message holding an answered tool part, the action continues that turn instead of starting the next one. It yields more parts into the same message: the tool's result, then the follow-up.
export async function* reply(messages: Message[]): AsyncGenerator<Part> {
const last = messages.at(-1);
const call = last?.role === 'assistant' ? last.parts.findLast((p) => p.type === 'tool') : undefined;
if (call?.type === 'tool' && call.name === 'archiveDrafts') {
if (!call.approved) {
yield { ...call, state: 'output-denied' };
return;
}
yield { ...call, state: 'output-available', output: { archived: 3 } };
yield* words('done', 'text', 'Archived 3 drafts.');
return;
}
// ...otherwise, the next scripted turn.
}
For a tool the person answers, the answer is the part's output. For an approval, it is approved. Keep the continuation a function of the transcript, so sending the same transcript again takes the same branch.
Client Wiring
The component writes the person's answer into the paused part, then streams the next reply into the same assistant message.
private async decide(part: Extract<Part, { type: 'tool' }>, approved: boolean) {
const id = this.messages.get().at(-1)!.id; // The paused assistant message.
this.update(id, { ...part, approved });
await this.stream(id, this.messages.get());
}
// In the tool part's renderer.
html`<button @click=${() => this.decide(part, true)}>Approve</button>
<button @click=${() => this.decide(part, false)}>Deny</button>`
A tool the person answers works the same way, with { ...part, state: 'output-available', output: { answers } } in place of the approval.
Data
Yield a data part for structured output your UI renders as a card.
yield {
id: 'weather-sf',
type: 'data',
name: 'weather',
data: { city: 'San Francisco', status: 'loading' },
};
Yield the same id again to update the part in place. This is useful for states such as loading to success.
yield {
id: 'weather-sf',
type: 'data',
name: 'weather',
data: { city: 'San Francisco', status: 'success', temperature: 27, condition: 'Breezy' },
};
For an update that should reach the component but not stay in the message, such as a status line, give it a chunk type of its own and have the loop write it to a separate signal instead of the message.
Files
Add files to a user message as parts.
const user: Message = {
id: crypto.randomUUID(),
role: 'user',
parts: [
{ id: 'text', type: 'text', text: 'Summarize this report.' },
{ id: 'report', type: 'file', filename: 'report.pdf', mediaType: 'application/pdf', url: 'https://example.com/report.pdf' },
],
};
A file the person picks can also travel as the File itself, in a file: File field on the part, since action arguments round-trip File and Blob values. Yield a file part to attach one to the assistant's message.
yield { id: 'summary', type: 'file', filename: 'summary.md', mediaType: 'text/markdown', url: 'https://example.com/summary.md' };
Sources
Yield a source part for each source the reply cites.
yield { id: 'source-1', type: 'source', title: 'Release notes', url: 'https://example.com/releases' };
Render them with the Sources pattern.
Step Starts
A step boundary is one more member of your part type. Yield it between steps, and draw it as a divider.
yield { id: 'step-2', type: 'step-start' };
Custom Parts
Any other part is the same: add a member to the Part union and a case to the renderer. Whatever the serializer carries crosses the wire.
Reading Messages
The transcript is the component's signal. Read it like any array.
this.messages.get(); // Every message.
this.messages.get().slice(0, 2); // The first two messages.
The next scripted question is the entry after the questions already sent, or undefined when none remain.
const sent = this.messages.get().filter((m) => m.role === 'user').length;
const next = questions[sent];
Start from Existing Messages
To open on a saved conversation, declare the transcript as a reactive property instead of a signal and pass it from the page. The page renders the saved thread on the server, and the property arrives with the element when it hydrates.
export class ScriptedChat extends WebComponent({
messages: prop<Message[]>(Array),
}) {
constructor() {
super();
this.messages = [];
}
// ...writes become this.messages = [...this.messages, message]
}
// app/chat/page.ts
const saved = await loadConversation(params.id);
return html`<scripted-chat .messages=${saved}></scripted-chat>`;
The action keys its script on the transcript it receives, so it continues from wherever the saved conversation stops.
Transport
The import is the transport. In the browser, importing a 'use server' file gives you an RPC stub, so await reply(transcript) sends the transcript to the server in one POST and resolves to an async iterable once the response starts. Each value the action yields is serialized with the same wire format action results use (so a Date, Map, Set, File or Blob arrives as itself) and flushed as it is produced.
To stop a reply, break out of the loop. That cancels the response, and the server stops pulling the generator. Inside the action, actionSignal() from @webjsdev/server aborts when the person cancels, so pass it on to any upstream request.
for await (const part of await reply(transcript)) {
if (this.stopped) break;
this.update(id, part);
}
To answer from a real model, the same action can call the AI SDK's streamText (from the ai package) on the server and yield parts as its stream produces them. No client package is needed, since the component is a WebComponent. See the AI SDK docs for the stream it returns.
Options
The stub takes no options. The call is one request to your own server, and the pace of the reply is set in the action. See Timing.
Fallback
When the script has no reply left for the transcript, have the action yield one anyway. This keeps a demo usable after its scripted replies are exhausted.
export async function* reply(messages: Message[]): AsyncGenerator<Part> {
const turn = turns[messages.filter((m) => m.role === 'user').length - 1];
if (!turn) {
yield { id: 'text', type: 'text', text: `This example already has ${messages.length} messages.` };
return;
}
yield* turn();
}
The fallback receives the transcript like every other reply, so it can answer from the current state.
Timing
Use delays in the action to reproduce the pace of a real response.
async function* () {
await sleep(800);
yield { id: 'first', type: 'text', text: 'The first milestone is complete.' };
await sleep(500);
yield* words('next', 'text', 'The next one is ready.');
}
await sleep(ms)before the first yield waits before the reply starts.await sleep(ms)between yields waits between parts, or between a tool's input and its result.- The last argument of
words()sets the delay between words. - Yielding a whole part once sends it in one chunk.
For fast tests, read the delay from an environment variable in the action and set it to 0.
Errors
Throw from the action when the reply should fail. A throw after parts have streamed ends the response with an error frame, and the component's for await loop throws, so the parts already applied stay on screen. Catch it there, and show it from an error signal on the component.
yield* words('text', 'text', 'I found the report.');
throw new Error('The connection closed before it could be read.');
try {
await this.stream(id, transcript);
} catch (error) {
this.error.set(error instanceof Error ? error.message : String(error));
}
In development the error carries your message. In production it carries a generic message and a digest, and the full error is logged on the server. When the reader should see the words, yield them as a part instead of throwing.
Metadata and IDs
Metadata is a field you add to the Message type. It crosses the wire as it is, rich types included.
export interface Message {
id: string;
role: 'user' | 'assistant';
parts: Part[];
metadata?: { model: string; createdAt: Date };
}
The component mints message ids with crypto.randomUUID() when it adds a message. Part ids are the action's, and they matter: a chunk whose id the message already holds replaces that part instead of adding one. For a fixture with fixed ids, write them into the script.
API Reference
The pieces are the streaming action, the stub the browser gets for it, and the kit's message scroller.
Streaming Action
RPC Stub
Message Scroller
See Message Scroller for the full reference.
Types
The Message and Part types are yours. The ones this page uses are under Message Parts.