An assistant chat
Past chats in the list column, the open one beside it, answers that think, stream and cite, an agent run that asks before it acts
Copy the file below whole (src/screens/chat.tsx) beside frame.tsx (docs/screen-frame.md), add the frame block's row to the frame's NAVIGATION before Settings (node goop/agent/start.mjs chat does it), and swap the sample chats for yours; keep the parts and their props. Use it for an assistant a person asks about their own notes and files, or an agent that runs tools for them; a conversation between people is docs/screen-inbox.md. The reference holds no chat screen: this one is Meadow's chat parts as they compose themselves, in Meadow's frame. 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 notes it cites to onDone, and return the stop (aborting your request); the screen stays as it is.
The list column (the frame's 244 px AppFramePanel size="list"): its header row (the frame's navigation button below the breakpoint, the column's name, the list toggle), New chat, then each past chat by its title, the open one washed. The open chat is the page beside it (AppFrameSecondPanel), held to Meadow's reading column: the thread (MessageList, opening at its newest message) with the prompt box at its foot (the frame scroll="panel", so the box stays put and the thread scrolls by itself). A question reads in the heading type at the start (ChatMessage variant="question"), its answer under it with no avatar. An answer thinks (ReplyStatus: the turning sparkle and what it is doing), shows the typing dots, then streams (streaming: each new word fades in) while the send is the stop (ComposerSubmit streaming onStop); whole, it keeps a "Thought for 2s" line whose press shows its steps, a Citation after each claim and the notes in a CitationList under it, each linking to the note's page (docs/screen-record.md), and ReplyActions (copy, good and bad, try again). An agent's steps are ToolCall rows before its words; before anything with an effect outside the chat it stops in an ApprovalRequest, the call in a CodeBlock: Approve runs it (its ToolCall running, then done, in the next answer), Deny runs nothing and says so. Enter sends and Shift+Enter starts a new line; the send waits for words. A new chat suggests a few prompts; a press sends one, and the first message names the chat. Choosing another chat stops an answer still arriving. Below 768 px the open chat takes the list's place, its back control returning. Light, dark, phone and desktop are the parts' own: add no class for them.
Show the code607 lines
// src/screens/chat.tsx: the assistant, past chats in the list column, the open one beside it with the prompt box
import { type KeyboardEvent, useEffect, useRef, useState } from 'react';
import {
AppFrameListToggle,
AppFramePanel,
AppFrameSecondPanel,
AppFrameTrigger,
} 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 { 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 { SidebarContent, SidebarHeader, SidebarHeaderRow, SidebarTitle } from '@/components/ui/goop/sidebar';
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 chat: the call, and the answer. */
interface Ask {
title: string;
tool: Tool;
decision: ApprovalDecision;
}
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 did while it thought, behind its status line, and for how many seconds. */
steps?: readonly string[];
thought?: number;
/** The notes 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 note an answer cites: a link to its page in your app. */
const note = (id: string, title: string): CitationSource => ({
id,
title,
site: 'Fieldwork notes',
icon: 'file-text',
href: hrefOf(`/notes/${id}`),
});
const HEDGE = note('FW-121', 'Hedgerow planting plan');
const SOIL = note('FW-117', 'Soil sample results');
const DRAINAGE = note('FW-112', 'Drainage survey debrief');
const ORCHARD = note('FW-110', 'Riverside orchards check-in');
/** The event the sample agent would add, as its call. */
const ADD: Tool = {
name: 'add_event',
state: 'running',
summary: 'Adding 1 event',
input: { title: 'Hedge planting', day: '2026-12-01', start: '10:00', end: '12:00' },
};
const CHATS: Chat[] = [
{
id: 'lime',
title: 'Lime for the lower beds',
messages: [
{
id: 'lime-1',
from: 'you',
text: 'Do the lower beds need lime before spring?',
time: '09:40',
dateTime: '2026-11-24T09:40',
},
{
id: 'lime-2',
from: 'assistant',
text: 'Yes: the lower beds read slightly acid,[1] so lime them before the spring sowing. The hedgerow plan keeps its hawthorn and hazel on the north edge, away from the limed ground.[2]',
time: '09:40',
dateTime: '2026-11-24T09:40',
turn: 'done',
steps: ['Searching your notes', 'Reading Soil sample results and Hedgerow planting plan'],
thought: 3,
sources: [SOIL, HEDGE],
},
],
},
{
id: 'hedge',
title: 'Book the hedge planting',
messages: [
{
id: 'hedge-1',
from: 'you',
text: 'Put the hedge planting on the calendar for Tuesday.',
time: '10:02',
dateTime: '2026-11-25T10:02',
},
{
id: 'hedge-2',
from: 'assistant',
text: 'Tuesday 1 December is free from ten. The event is ready: it goes on the calendar once you approve it.',
time: '10:02',
dateTime: '2026-11-25T10:02',
turn: 'done',
steps: ['Reading Tuesday’s calendar'],
thought: 2,
tools: [
{
name: 'find_free_time',
state: 'done',
summary: 'Free from 10:00',
input: { day: '2026-12-01' },
output: '10:00 to 16:00 free',
},
],
ask: { title: 'Add “Hedge planting” to Tuesday 1 December, 10:00 to 12:00', tool: ADD, decision: 'pending' },
},
],
},
{
id: 'orchard',
title: 'Orchard pruning order',
messages: [
{
id: 'orchard-1',
from: 'you',
text: 'Which orchard trees need pruning first?',
time: '16:12',
dateTime: '2026-11-23T16:12',
},
{
id: 'orchard-2',
from: 'assistant',
text: 'The two old pear trees by the river: they need a hard prune before the sap rises.[1] The apples set well this year and can wait.[1]',
time: '16:12',
dateTime: '2026-11-23T16:12',
turn: 'done',
steps: ['Reading Riverside orchards check-in'],
thought: 2,
sources: [ORCHARD],
},
],
},
];
// ---- 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 this week’s notes',
answer: {
text: 'Three notes changed this week. The hedgerow plan sets hawthorn and hazel along the north edge;[1] the lower beds need lime before sowing;[2] and the east ditch culvert is to be cleared first.[3]',
sources: [HEDGE, SOIL, DRAINAGE],
},
},
{
prompt: 'What should the crew do first?',
answer: {
text: 'Clear the east culvert: the ditch holds water after rain, and the beds beside it stay wet until it runs.[1] Then lime the lower beds.[2]',
sources: [DRAINAGE, SOIL],
},
},
{
prompt: 'Draft a note for the orchard crew',
answer: {
text: 'Orchard crew,\nThe two old pear trees by the river need a hard prune before the sap rises.[1] The apples can wait until spring.\nThank you, Teodora',
sources: [ORCHARD],
},
},
];
/** 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 note it draws on.[2]',
sources: [HEDGE, SOIL],
};
/** 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 notes 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');
onStep(`Reading the ${answer.sources.length} notes 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 (
<>
<p>
{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} />;
})}
</p>
<CitationList sources={sources} />
</>
);
}
/** 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() };
}
/** 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);
// below the breakpoint: whether the open chat holds the window (the list does until one is chosen)
const [reading, setReading] = useState(false);
const [draft, setDraft] = useState('');
// the answer arriving now (one at a time), when it began, and its stop; the approved tool's run
const [answering, setAnswering] = useState<{ chat: string; message: string } | null>(null);
const began = useRef(0);
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)),
);
/** The seconds the answer arriving now has taken, at least one. */
const seconds = () => Math.max(1, Math.round((Date.now() - began.current) / 1000));
/** 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 });
began.current = Date.now();
stopReply.current = reply(prompt, {
onStep: (step) => changeMessage(chatId, id, (one) => ({ steps: [...(one.steps ?? []), step] })),
onText: (text) =>
changeMessage(chatId, id, (one) => ({ text, turn: 'streaming', thought: one.thought ?? seconds() })),
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',
thought: one.thought ?? seconds(),
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: [],
thought: undefined,
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 answer; denied, none. */
const decide = (chat: Chat, message: Message, decision: ApprovalDecision) => {
const { ask: asked } = message;
if (!asked) return;
changeMessage(chat.id, message.id, () => ({ ask: { ...asked, decision } }));
made.current += 1;
const id = `run-${made.current}`;
const approved = decision === 'approved';
addMessages(chat.id, [
{
id,
from: 'assistant',
turn: 'done',
text: approved ? '' : 'Nothing was added. Ask again when the day is settled.',
tools: approved ? [asked.tool] : undefined,
...now(),
},
]);
if (!approved) return;
toolTimer.current = setTimeout(
() =>
changeMessage(chat.id, id, () => ({
text: 'Done: Hedge planting is on Tuesday’s calendar, from 10:00 to 12:00.',
tools: [{ ...asked.tool, state: 'done', summary: 'Added 1 event', output: { added: 1 } }],
})),
TOOL_MS,
);
};
const choose = (id: string | null) => {
stop();
setOpenId(id);
setReading(true);
setDraft('');
};
/** An answer's words: thinking, the typing dots, the words arriving, then whole with its status, 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 (
<>
{message.thought ? <ReplyStatus state="done" elapsed={message.thought} steps={message.steps} /> : null}
{tools ? (
<div className="flex flex-col gap-0.5">
{tools.map((tool) => (
<ToolCall key={tool.name} {...tool} />
))}
</div>
) : null}
{sources?.length ? (
<CitedWords text={message.text} sources={sources} />
) : message.text ? (
<p>{plain(message.text)}</p>
) : null}
{asked ? (
<ApprovalRequest
title={asked.title}
description={`The assistant wants to run ${asked.tool.name}.`}
decision={asked.decision}
onApprove={() => decide(chat, message, 'approved')}
onDeny={() => decide(chat, message, 'denied')}
>
<CodeBlock code={JSON.stringify(asked.tool.input, null, 2)} language="json" wrap />
</ApprovalRequest>
) : null}
</>
);
};
return (
<ScreenFrame current="/chat" scroll="panel">
<AppFramePanel
size="list"
aria-label="Chats"
header={
<SidebarHeader>
<SidebarHeaderRow>
<AppFrameTrigger />
<SidebarTitle>Assistant</SidebarTitle>
<AppFrameListToggle />
</SidebarHeaderRow>
</SidebarHeader>
}
>
<SidebarContent>
<SidebarGroup>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton icon="edit" isActive={!open} onClick={() => choose(null)}>
New chat
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
<SidebarGroup>
<SidebarGroupLabel>Chats</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu aria-label="Chats">
{chats.map((chat) => (
<SidebarMenuItem key={chat.id}>
<SidebarMenuButton isActive={chat.id === openId} onClick={() => choose(chat.id)}>
{chat.title}
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
</AppFramePanel>
<AppFrameSecondPanel
aria-label={open?.title ?? 'New chat'}
open={reading}
onOpenChange={setReading}
closeLabel="Back to the chats"
header={<ScreenTopBar title={open?.title ?? 'New chat'} />}
>
<PageBody gutter="page" spaced={false}>
<div className={`mx-auto flex min-h-0 w-full max-w-page-reading grow flex-col ${pageRoles.block}`}>
{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"
variant="question"
author="You"
time={message.time}
dateTime={message.dateTime}
>
{message.text}
</ChatMessage>
) : (
<ChatMessage
key={message.id}
author="Assistant"
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 ${pageRoles.top} ${pageRoles.block}`}>
<Empty>
<EmptyHeader>
<EmptyTitle>Ask about your notes</EmptyTitle>
<EmptyDescription>The answers here are samples, each with the notes 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>
</div>
</PageBody>
</AppFrameSecondPanel>
</ScreenFrame>
);
}`tsx frame { words: 'Assistant', path: '/chat', icon: 'tabler-outline:sparkle-2' },