---
agent:
  instructions: "Search goop.so for Goop's components, templates, design skill, docs, pricing and terms. Ask in keywords or a plain question, such as \"date picker props\" or \"is the design skill free\"; the answer is the matching page sections in Markdown, each with its address."
  endpoint: "https://goop.so/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# An assistant chat

Past chats, the thread with answers streaming in and the sources they cite, an agent run that asks before it acts, the prompt box

Copy the file below whole (`src/screens/chat.tsx`) beside `frame.tsx` (`docs/screen-frame.md`), whose pages hold `/chat`, and swap the sample chats for yours; keep the parts and their props. Use it for an assistant a person asks about their own documents (a research, support or writing assistant), or an agent that runs tools for them; a conversation between people is `docs/screen-inbox.md`. The assistant here gives SAMPLE REPLIES: `reply()` streams a fixed answer word by word on a timer, and nothing is sent anywhere (no network, no key, no model). To connect your model, replace `reply()`'s body alone: pass what it does while it thinks to `onStep`, each piece of text as it arrives to `onText` (the words so far, a citation as `[n]` after its claim), the documents it cites, in that order, to `onDone`, and return the stop (aborting your request); the screen stays as it is.

The chats stand in the sidebar under the pages (ScreenFrame's `more`): New chat first, then each past chat by its title, the open one marked. The open chat is the panel: its title in the top bar, the thread (MessageList: the person's messages at the end in a fill, the assistant's from the start beside its avatar), the prompt box at the foot (`PageBody gutter="page" spaced={false}`, the frame `scroll="panel"`, so the box stays at the foot and the thread scrolls by itself, opening at its newest message). Enter sends and Shift+Enter starts a new line (the editor's `onKeyDown` below; Cmd or Ctrl+Enter sends too); the send waits for words. An answer thinks, then streams (`streaming`: each new word fades in, the thread follows it); meanwhile the send is the stop (`ComposerSubmit streaming onStop`), which ends it where it is. A whole answer's sources link to their documents' pages (`hrefOf('/files/<id>')`: a record's page you write from `docs/screen-record.md`). A new chat suggests a few prompts over the box; a press sends one, and the first message names the chat. Choosing another chat stops an answer still arriving. Light, dark, phone and desktop are the parts' own: add no class for them.

Which part, when:

- [chat.reply] An AI answer: ReplyStatus while it thinks, ReplyTyping until its first word, a Citation after each claim with a source and a CitationList of them under its words, and ReplyActions in its `actions` once it is whole. ChatMessage's own props are for people's messages: `sources` for files a message carries (a person's attachments, never on an answer beside a CitationList), `status` for a message sending or failed, ChatMessageCopy and ChatMessageThinking where no rating fits.
- [agent.run] An agent's steps are ToolCall rows inside its message, folded once done; before anything with an effect outside the app (send, pay, delete) it stops in an ApprovalRequest, the call in a CodeBlock. Only Approve runs it: its ToolCall shows Running, then Done, in the next message; Deny runs nothing and says so. The past chat "Reminders for Thursday's visits" is such a run. Your agent: a ToolCall per call as its events arrive, the ApprovalRequest where it waits; call the tool in `onApprove`, hand the refusal (and its reason) back to the agent in `onDeny`.

```tsx
// src/screens/chat.tsx: the assistant chat
import { type KeyboardEvent, useEffect, useRef, useState } from 'react';
import { AppFramePanel } from '@/components/goop/patterns/app-frame';
import { PageBody, pageRoles } from '@/components/goop/patterns/page-body';
import { type ApprovalDecision, ApprovalRequest } from '@/components/ui/goop/approval-request';
import { Avatar } from '@/components/ui/goop/avatar';
import { Button } from '@/components/ui/goop/button';
import { ChatMessage } from '@/components/ui/goop/chat-message';
import { Citation, CitationList, type CitationSource } from '@/components/ui/goop/citation';
import { CodeBlock } from '@/components/ui/goop/code-block';
import {
  Composer,
  ComposerActions,
  ComposerEditor,
  ComposerSubmit,
  ComposerToolbar,
} from '@/components/ui/goop/composer';
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from '@/components/ui/goop/empty';
import { MessageList } from '@/components/ui/goop/message-list';
import { ReplyActions, type ReplyRating } from '@/components/ui/goop/reply-actions';
import { ReplyStatus, ReplyTyping } from '@/components/ui/goop/reply-status';
import {
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuItem,
} from '@/components/ui/goop/sidebar-group';
import { SidebarMenuButton } from '@/components/ui/goop/sidebar-menu-button';
import { ToolCall, type ToolCallState } from '@/components/ui/goop/tool-call';
import { ScreenFrame, ScreenTopBar } from './frame';
import { hrefOf } from './router';

// ---- the sample data: swap it for yours
/** Where an answer is: thinking, arriving (no words yet: the typing dots), whole, or stopped by the person. */
type Turn = 'thinking' | 'streaming' | 'done' | 'stopped';
/** One call an agent made, as ToolCall draws it. */
interface Tool {
  name: string;
  state: ToolCallState;
  summary: string;
  input: unknown;
  output?: unknown;
}
/** What an agent asks before a step with an effect outside the app: the call, and the answer. */
interface Ask {
  title: string;
  tool: Tool;
  decision: ApprovalDecision;
  reason?: string;
}
interface Message {
  id: string;
  from: 'you' | 'assistant';
  /** The words; in an answer, `[n]` after a claim cites its nth source. */
  text: string;
  /** The time as the thread shows it ("09:41"), and for a machine. */
  time: string;
  dateTime: string;
  /** An answer's state; a past answer is `done`. */
  turn?: Turn;
  /** What the assistant does while it thinks, behind its status line. */
  steps?: readonly string[];
  /** The documents an answer cites, numbered from 1; shown once it is whole. */
  sources?: readonly CitationSource[];
  rating?: ReplyRating | null;
  /** An agent run: the tools it called, and what it waits for your yes on. */
  tools?: readonly Tool[];
  ask?: Ask;
}
interface Chat {
  id: string;
  title: string;
  messages: Message[];
}
/** A document an answer cites: a link to its page in your app, under where it lives. */
const file = (id: string, title: string, site: string, icon: CitationSource['icon'] = 'file-text'): CitationSource => ({
  id,
  title,
  site,
  icon,
  href: hrefOf(`/files/${id}`),
});
const NOTES = file('interview-notes-week-46', 'Interview notes, week 46', 'Diallo Dental');
const FORM = file('consent-form', 'Consent form wording', 'Diallo Dental', 'file-type-pdf');
const SIGN_UPS = file('clinic-sign-ups', 'Clinic sign-ups', 'Diallo Dental', 'file-spreadsheet');
const SURVEY = file('visitor-survey', 'Visitor survey results', 'Eastgate Library', 'file-spreadsheet');
const DESK = file('front-desk-notes', 'Front desk notes', 'Eastgate Library');
/** The reminders the sample agent would send, as its call. */
const SEND: Tool = {
  name: 'send_reminders',
  state: 'running',
  summary: 'Sending 4 emails',
  input: { site: 'Diallo Dental', day: '2026-12-03', to: 4 },
};
const CHATS: Chat[] = [
  {
    id: 'consent',
    title: 'Consent step in the interviews',
    messages: [
      {
        id: 'consent-1',
        from: 'you',
        text: 'What did the Diallo Dental interviews say about the consent step?',
        time: '09:40',
        dateTime: '2026-11-27T09:40',
      },
      {
        id: 'consent-2',
        from: 'assistant',
        text: 'Seven of the eleven interviews mention it.[1] Most patients signed on paper at the front desk and found the tablet form slow: its checkbox is hard to tick at a large text size.[2] Two asked to read the form at home first.[3]',
        time: '09:40',
        dateTime: '2026-11-27T09:40',
        turn: 'done',
        sources: [NOTES, FORM, SIGN_UPS],
      },
    ],
  },
  {
    id: 'reminders',
    title: 'Reminders for Thursday’s visits',
    messages: [
      {
        id: 'reminders-1',
        from: 'you',
        text: 'Remind everyone booked at Diallo Dental on Thursday.',
        time: '10:02',
        dateTime: '2026-11-30T10:02',
      },
      {
        id: 'reminders-2',
        from: 'assistant',
        text: 'Four people are booked on Thursday. The reminder is written; it goes out once you approve it.',
        time: '10:02',
        dateTime: '2026-11-30T10:02',
        turn: 'done',
        tools: [
          {
            name: 'find_visits',
            state: 'done',
            summary: 'Found 4 visits',
            input: { site: 'Diallo Dental', day: '2026-12-03' },
            output: 'Amara Osei 09:00\nBilal Rashed 10:30\nNgozi Ilori 13:00\nWulan Sari 15:30',
          },
        ],
        ask: { title: 'Send the reminder email to 4 participants', tool: SEND, decision: 'pending' },
      },
    ],
  },
  {
    id: 'library',
    title: 'Eastgate Library visitor survey',
    messages: [
      {
        id: 'library-1',
        from: 'you',
        text: 'Sum up the Eastgate Library visitor survey in three lines.',
        time: '16:12',
        dateTime: '2026-11-26T16:12',
      },
      {
        id: 'library-2',
        from: 'assistant',
        text: 'Most visitors come on weekday mornings, for the study rooms.[1]\nThe queue at the returns desk is the top complaint: over ten minutes at peak hours.[2]\nSeveral asked for the opening hours on the front door.[1]',
        time: '16:12',
        dateTime: '2026-11-26T16:12',
        turn: 'done',
        sources: [SURVEY, DESK],
      },
    ],
  },
];

// ---- the assistant: SAMPLE REPLIES from a fixed list, nothing sent; replace `reply`'s body with your model's call
interface Answer {
  text: string;
  sources: readonly CitationSource[];
}
/** The prompts a new chat suggests, each with its sample answer. */
const SUGGESTED: readonly { prompt: string; answer: Answer }[] = [
  {
    prompt: 'Sum up last week’s interviews',
    answer: {
      text: 'Eleven interviews last week, at Diallo Dental and Eastgate Library.[1] The consent step came up most: seven people found the tablet form slow.[2] Four asked for a reminder the day before a visit, and three praised the shorter check-in.[1]',
      sources: [NOTES, FORM],
    },
  },
  {
    prompt: 'Which customers asked for reminders?',
    answer: {
      text: 'Diallo Dental and Eastgate Library both did. Diallo Dental wants a text the day before each visit;[1] Eastgate Library asked for an email a week ahead of a room booking.[2]',
      sources: [SIGN_UPS, DESK],
    },
  },
  {
    prompt: 'Draft an update for Eastgate Library',
    answer: {
      text: 'Hello Eastgate Library team,\nThe visitor survey is in: 214 answers.[1] Weekday mornings are the busiest, and the returns desk queue is the top complaint.[1] We will share three ways to shorten it at Friday’s review.\nBest wishes, Teodora Valk',
      sources: [SURVEY],
    },
  },
];
/** The sample answer to any other prompt. */
const ANY_ANSWER: Answer = {
  text: 'This is a sample reply: the assistant on this screen answers from a fixed list until it is connected to a model.[1] Its answers then stream in here the same way, each claim numbered with the document it draws on.[2]',
  sources: [NOTES, SURVEY],
};
/** How long the sample thinks, then shows the typing dots, then waits between its words, in ms. */
const THINKING_MS = 700;
const TYPING_MS = 300;
const WORD_MS = 45;
/** How long the sample's tool takes once approved, in ms. */
const TOOL_MS = 900;

/**
 * The answer to `prompt` as it arrives: `onStep` for each thing it does while it thinks, `onText` with the words so far
 * (`''` once it writes), `onDone` with the documents it cites; returns the stop. SAMPLE REPLIES on a timer.
 */
function reply(
  prompt: string,
  {
    onStep,
    onText,
    onDone,
  }: {
    onStep: (step: string) => void;
    onText: (text: string) => void;
    onDone: (sources: readonly CitationSource[]) => void;
  },
): () => void {
  const answer = SUGGESTED.find((one) => one.prompt === prompt)?.answer ?? ANY_ANSWER;
  onStep('Searching your notes and files');
  onStep(`Reading the ${answer.sources.length} documents that answer it`);
  const words = answer.text.split(' ');
  let shown = 0;
  let timer: ReturnType<typeof setTimeout>;
  const next = () => {
    shown += 1;
    onText(words.slice(0, shown).join(' '));
    if (shown < words.length) timer = setTimeout(next, WORD_MS);
    else onDone(answer.sources);
  };
  timer = setTimeout(() => {
    onText('');
    timer = setTimeout(next, TYPING_MS);
  }, THINKING_MS);
  return () => clearTimeout(timer);
}

/** `[n]` in an answer's words: its nth source. */
const MARK = /\[(\d+)\]/g;
/** An answer's words without its marks: while they stream, and what Copy writes. */
const plain = (text: string) => text.replace(MARK, '');

/** A whole answer's words, a Citation chip at each mark, and the same sources numbered alike in the row under them. */
function CitedWords({ text, sources }: { text: string; sources: readonly CitationSource[] }) {
  return (
    <>
      {text.split(MARK).map((piece, index) => {
        if (index % 2 === 0) return piece;
        const source = sources[Number(piece) - 1];
        if (!source) return null;
        // biome-ignore lint/suspicious/noArrayIndexKey: a whole answer's words never change
        return <Citation key={index} index={Number(piece)} source={source} />;
      })}
      <CitationList sources={sources} className="mt-2" />
    </>
  );
}

/** The clock now, as a message's time ("09:41") and for a machine. */
function now(): { time: string; dateTime: string } {
  const at = new Date();
  return { time: at.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }), dateTime: at.toISOString() };
}

const ASSISTANT_AVATAR = (
  <Avatar variant="solid" name="Assistant" aria-hidden="true">
    AI
  </Avatar>
);

/** Enter sends the prompt; Shift+Enter (and Enter while a word is being composed) writes a new line. */
function sendOnEnter(event: KeyboardEvent<HTMLTextAreaElement>) {
  if (event.key !== 'Enter' || event.shiftKey || event.nativeEvent.isComposing) return;
  event.preventDefault();
  event.currentTarget.form?.requestSubmit();
}

export default function ChatScreen() {
  const [chats, setChats] = useState(CHATS);
  const [openId, setOpenId] = useState<string | null>(CHATS[0]?.id ?? null);
  const [draft, setDraft] = useState('');
  // the answer arriving now (one at a time), and its stop; the approved tool's run
  const [answering, setAnswering] = useState<{ chat: string; message: string } | null>(null);
  const stopReply = useRef<(() => void) | null>(null);
  const toolTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
  const made = useRef(0);
  // nothing keeps arriving once the screen is gone
  useEffect(
    () => () => {
      stopReply.current?.();
      clearTimeout(toolTimer.current);
    },
    [],
  );
  const open = chats.find((chat) => chat.id === openId);

  const changeMessage = (chatId: string, id: string, next: (message: Message) => Partial<Message>) =>
    setChats((all) =>
      all.map((chat) =>
        chat.id === chatId
          ? { ...chat, messages: chat.messages.map((one) => (one.id === id ? { ...one, ...next(one) } : one)) }
          : chat,
      ),
    );
  const addMessages = (chatId: string, messages: Message[]) =>
    setChats((all) =>
      all.map((chat) => (chat.id === chatId ? { ...chat, messages: [...chat.messages, ...messages] } : chat)),
    );
  /** Streams the answer to `prompt` into the answer `id` of chat `chatId`. */
  const answer = (chatId: string, id: string, prompt: string) => {
    setAnswering({ chat: chatId, message: id });
    stopReply.current = reply(prompt, {
      onStep: (step) => changeMessage(chatId, id, (one) => ({ steps: [...(one.steps ?? []), step] })),
      onText: (text) => changeMessage(chatId, id, () => ({ text, turn: 'streaming' })),
      onDone: (sources) => {
        stopReply.current = null;
        setAnswering(null);
        changeMessage(chatId, id, () => ({ turn: 'done', sources }));
      },
    });
  };
  /** Ends the answer arriving now where it is: its words so far stay, with no sources. */
  const stop = () => {
    stopReply.current?.();
    stopReply.current = null;
    if (!answering) return;
    setAnswering(null);
    changeMessage(answering.chat, answering.message, (one) => ({
      turn: 'stopped',
      text: plain(one.text) || 'Stopped before an answer.',
    }));
  };
  /** Sends a prompt into the open chat, or a new one named by it, and asks the assistant. */
  const ask = (text: string) => {
    const prompt = text.trim();
    if (!prompt || answering) return;
    made.current += 1;
    const at = now();
    const question: Message = { id: `asked-${made.current}`, from: 'you', text: prompt, ...at };
    const pending: Message = { id: `answer-${made.current}`, from: 'assistant', text: '', turn: 'thinking', ...at };
    const chatId = open?.id ?? `chat-${made.current}`;
    if (open) addMessages(open.id, [question, pending]);
    else {
      setChats((all) => [
        { id: chatId, title: prompt.split('\n')[0] ?? prompt, messages: [question, pending] },
        ...all,
      ]);
      setOpenId(chatId);
    }
    setDraft('');
    answer(chatId, pending.id, prompt);
  };
  /** Asks again for an answer: the prompt before it, its words, sources and rating replaced. */
  const retry = (chat: Chat, id: string) => {
    const at = chat.messages.findIndex((one) => one.id === id);
    const prompt = chat.messages[at - 1]?.text;
    if (!prompt) return;
    stop();
    changeMessage(chat.id, id, () => ({
      text: '',
      sources: undefined,
      steps: [],
      rating: null,
      turn: 'thinking',
      ...now(),
    }));
    answer(chat.id, id, prompt);
  };
  /** The answer to the agent's ask: approved, its call runs (SAMPLE: a timer) in a new message; denied, none. */
  const decide = (chat: Chat, message: Message, decision: ApprovalDecision, reason?: string) => {
    const { ask: asked } = message;
    if (!asked) return;
    changeMessage(chat.id, message.id, () => ({ ask: { ...asked, decision, reason } }));
    made.current += 1;
    const id = `run-${made.current}`;
    const approved = decision === 'approved';
    addMessages(chat.id, [
      {
        id,
        from: 'assistant',
        turn: 'done',
        text: approved ? '' : 'Nothing was sent. Ask again when the reminders should go out.',
        tools: approved ? [asked.tool] : undefined,
        ...now(),
      },
    ]);
    if (!approved) return;
    toolTimer.current = setTimeout(
      () =>
        changeMessage(chat.id, id, () => ({
          text: 'Sent: the four participants have their reminder for Thursday.',
          tools: [{ ...asked.tool, state: 'done', summary: 'Sent 4 emails', output: { sent: 4, failed: 0 } }],
        })),
      TOOL_MS,
    );
  };
  const choose = (id: string | null) => {
    stop();
    setOpenId(id);
    setDraft('');
  };
  /** An answer's words: thinking, the typing dots, the words arriving, then whole with its citations, tools and ask. */
  const answerWords = (chat: Chat, message: Message) => {
    if (message.turn === 'thinking') return <ReplyStatus steps={message.steps} />;
    if (message.turn === 'streaming') return plain(message.text) || <ReplyTyping />;
    const { sources, tools, ask: asked } = message;
    return (
      <>
        {sources?.length ? <CitedWords text={message.text} sources={sources} /> : plain(message.text)}
        {tools || asked ? (
          <div className="mt-2 flex flex-col gap-2">
            {tools?.map((tool) => (
              <ToolCall key={tool.name} {...tool} />
            ))}
            {asked ? (
              <ApprovalRequest
                title={asked.title}
                description={`The assistant wants to run ${asked.tool.name}.`}
                decision={asked.decision}
                reason={asked.reason}
                askReason
                onApprove={() => decide(chat, message, 'approved')}
                onDeny={(why) => decide(chat, message, 'denied', why)}
              >
                <CodeBlock code={JSON.stringify(asked.tool.input, null, 2)} language="json" wrap />
              </ApprovalRequest>
            ) : null}
          </div>
        ) : null}
      </>
    );
  };

  return (
    <ScreenFrame
      current="/chat"
      scroll="panel"
      more={
        <SidebarGroup>
          <SidebarGroupLabel>Chats</SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu>
              <SidebarMenuItem>
                <SidebarMenuButton size="sm" icon="edit" isActive={!open} onClick={() => choose(null)}>
                  New chat
                </SidebarMenuButton>
              </SidebarMenuItem>
              {chats.map((chat) => (
                <SidebarMenuItem key={chat.id}>
                  <SidebarMenuButton size="sm" isActive={chat.id === openId} onClick={() => choose(chat.id)}>
                    {chat.title}
                  </SidebarMenuButton>
                </SidebarMenuItem>
              ))}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      }
    >
      <AppFramePanel header={<ScreenTopBar title={open?.title ?? 'New chat'} />}>
        <PageBody gutter="page" spaced={false}>
          {open ? (
            // a chat opened afresh opens at its newest message
            <MessageList key={open.id} aria-label={open.title} inset={false} className={`grow ${pageRoles.top}`}>
              {open.messages.map((message, index) =>
                message.from === 'you' ? (
                  <ChatMessage
                    key={message.id}
                    from="self"
                    author="You"
                    time={message.time}
                    dateTime={message.dateTime}
                  >
                    {message.text}
                  </ChatMessage>
                ) : (
                  <ChatMessage
                    key={message.id}
                    author="Assistant"
                    avatar={ASSISTANT_AVATAR}
                    time={message.time}
                    dateTime={message.dateTime}
                    streaming={message.turn === 'streaming'}
                    actions={
                      message.turn === 'thinking' || message.turn === 'streaming' || !message.text ? undefined : (
                        <ReplyActions
                          text={plain(message.text)}
                          rating={message.rating ?? null}
                          onRate={(rating) => changeMessage(open.id, message.id, () => ({ rating }))}
                          // an answer to the question before it is asked again; an agent run's steps are not
                          onRetry={
                            open.messages[index - 1]?.from === 'you' && !message.ask
                              ? () => retry(open, message.id)
                              : undefined
                          }
                        />
                      )
                    }
                  >
                    {answerWords(open, message)}
                  </ChatMessage>
                ),
              )}
            </MessageList>
          ) : (
            <div className={`flex grow flex-col justify-end pb-4 ${pageRoles.top} ${pageRoles.block}`}>
              <Empty>
                <EmptyHeader>
                  <EmptyTitle>Ask about your interviews, notes and files.</EmptyTitle>
                  <EmptyDescription>
                    The answers here are samples, each with the documents it draws on.
                  </EmptyDescription>
                </EmptyHeader>
              </Empty>
              <ul aria-label="Suggested prompts" className={`flex flex-wrap ${pageRoles.row}`}>
                {SUGGESTED.map(({ prompt }) => (
                  <li key={prompt}>
                    <Button variant="outline" onClick={() => ask(prompt)}>
                      {prompt}
                    </Button>
                  </li>
                ))}
              </ul>
            </div>
          )}
          <Composer
            aria-label="Ask the assistant"
            onSubmit={(event) => {
              event.preventDefault();
              ask(draft);
            }}
          >
            <ComposerEditor
              aria-label="Message"
              placeholder="Ask about your notes…"
              value={draft}
              onChange={(event) => setDraft(event.target.value)}
              onKeyDown={sendOnEnter}
            />
            <ComposerToolbar>
              <ComposerActions>
                <ComposerSubmit
                  aria-label="Send"
                  disabled={!answering && !draft.trim()}
                  streaming={answering !== null}
                  onStop={stop}
                />
              </ComposerActions>
            </ComposerToolbar>
          </Composer>
        </PageBody>
      </AppFramePanel>
    </ScreenFrame>
  );
}
```
