Tulip Logo IconTulip
Concepts

Chat

Stream agent output on the server and render composable chat UI on the client.

The chat has two halves:

  • Chat on the server (see Services): saves the chats and streams the agent's response from a server procedure
  • chat/client: the useAssistantChat hook and composable React components for threads, messages, composers, and tool cards

Saving chats

Chat saves chats. chat.send() takes only what is new in a turn: a user message, or the user's answers to the approvals the last response waits for. It loads the earlier messages from the user's own chat, so a client cannot change the history the agent sees, builds the tool call, and saves the response when the stream ends, also when the user stops it. Wrap the stream with streamToEventIterator from oRPC:

import { streamToEventIterator } from "@orpc/server";

send: protectedProcedure
  .input(sendAssistantMessageSchema)
  .handler(async ({ context, input, signal }) =>
    streamToEventIterator(
      await chat.send({
        ...input,
        user: context.user,
        agent: "assistant",
        abortSignal: signal,
      }),
    ),
  ),

The input is an AiChatRequest: the chatId, a message or approvals, and the page context. message is { parts: [{ type: "text", text }] }. Send either message or approvals, never both. context is the page the chat was opened from (AgentContextValue); Chat only accepts a JSON object of at most 16,000 characters, and the agent adds it to its instructions. The chat is created on its first message, with that message as its title.

The response is an AI SDK UI message stream. It includes sources, for example web search citations.

The agent must be active: the chat of a new or turned off agent refuses messages. Each turn is recorded as a run with a chat trigger; answering approvals continues the run that waits for them.

Read and change chats with chat.list(), get(), rename() and delete(). approvals(userId, chatId, agentName) lists the tools approved for the whole chat that still ask otherwise, and revokeApproval() takes one back. waitsFor(userId, chatId, approvalId) says whether the chat waits for an approval, for example before asking for a passkey. On the client, send turns with useAssistantChat().

Client

useAssistantChat() is useChat for chats the server saves. It sends only what is new in a turn: the user's message, or their answers to the approvals the last response waits for. Give it the chatId, the chat's saved messages, and a send function that sends the request to the server and returns its stream:

"use client";

import { eventIteratorToUnproxiedDataStream } from "@orpc/client";
import { useAssistantChat } from "@tulip-systems/ai/chat/client";
import { useAgentContext } from "@tulip-systems/ai/context/client";
import { orpc } from "@/server/router/client";

const context = useAgentContext();

const chat = useAssistantChat({
  chatId,
  messages: initialMessages,
  context,
  send: async (request, { abortSignal }) =>
    eventIteratorToUnproxiedDataStream(
      await orpc.assistant.send.call(request, { signal: abortSignal }),
    ),
  onFinish: () => queryClient.invalidateQueries({ queryKey: orpc.assistant.key() }),
});

request is an AiChatRequest (from @tulip-systems/ai/types). Pass it on to chat.send(). context is the page the user opened the chat from; it is read when a turn is sent. useAgentContext() returns it as one object, merged from every <AgentContext value={...}> that is mounted inside the same AgentContextProvider.

The hook returns the fields of useChat (messages, status, error, stop and the rest) plus the composer's input, setInput and submit, and answerApproval for the thread. submit ignores empty input and does nothing while the assistant answers. Once every approval of the last response is answered, the hook sends the answers by itself.

The chat is created once per mount. Mount the component with key={chatId} to switch chats.

Thread composition

<ChatThread
  status={chat.status}
  answerApproval={chat.answerApproval}
  labels={ASSISTANT_CHAT_LABELS}
  toolRenderers={ASSISTANT_TOOL_RENDERERS}
>
  <ChatThreadContent>
    {chat.messages.map((message) => (
      <ChatThreadMessage key={message.id} message={message} />
    ))}
    <ChatThreadActivity />
  </ChatThreadContent>
</ChatThread>

Set labels and toolRenderers once on ChatThread. Every message, tool card and approval in the thread reads them. ChatThreadContent scrolls along with the response, and ChatThreadActivity shows typing dots while the assistant responds.

Labels

labels (ChatThreadLabels) holds the texts of the thread, to translate them:

import type { ChatThreadLabels } from "@tulip-systems/ai/chat/client";

export const ASSISTANT_CHAT_LABELS = {
  tool: {
    yes: "Ja",
    no: "Nee",
    preparing: "Voorbereiden",
    running: "Bezig",
    done: "Klaar",
    failed: "Mislukt",
    approval: { question: "Wil je dat de assistent dit uitvoert?", approve: "Goedkeuren" },
  },
  reasoning: { streaming: "Aan het nadenken", done: "Redenering" },
  sources: "Bronnen",
  activity: "De assistent is bezig",
} satisfies ChatThreadLabels;
  • tool: ToolCallCard, with approval for ToolApproval
  • reasoning: ChatReasoning
  • sources: the heading above a message's sources
  • activity: read to screen readers while the assistant responds

The components take no labels of their own. ChatComposer is the exception, with its own labels: attach, send, stop and wait.

Composer composition

<ChatComposer
  value={chat.input}
  onValueChange={chat.setInput}
  onSubmit={chat.submit}
  onStop={chat.stop}
  status={chat.status}
>
  <ChatComposerInput placeholder="Ask something..." />
  <ChatComposerToolbar>
    <ChatComposerActions>
      <ChatComposerAttachmentButton />
    </ChatComposerActions>
    <ChatComposerSubmit />
  </ChatComposerToolbar>
</ChatComposer>

ChatComposer keeps typing available while the agent is responding. Submit is disabled while the agent responds (submitted or streaming); after an error the user can send again. With onStop (stop from useAssistantChat), ChatComposerSubmit turns into a stop button while the status is submitted or streaming.

Messages

ChatThreadMessage renders a whole message. A user message is a plain-text bubble. An assistant message shows its text as GitHub flavored markdown (ChatMarkdown), its reasoning, a card per tool call, and its source links under the thread's labels.sources. A message with nothing to show renders nothing.

Reasoning parts render as a collapsed toggle (ChatReasoning) that shows the model's thinking, translated with the thread's labels.reasoning. Reasoning only appears when the model sends it, for example with OpenRouter's reasoning setting:

openrouter("anthropic/claude-sonnet-5.5", { reasoning: { effort: "low" } });

Approvals

Tools that ask first wait for the user's approval in the chat (see Approvals for approvals outside the chat). Pass answerApproval from useAssistantChat to ChatThread; the hook sends the answers once every approval is answered.

ToolCallCard shows ToolApproval for a call that waits: the question, an optional note for the agent, and Approve and Deny. Translate it with labels.tool.approval on ChatThread. Once answered it shows the decision, also for a call the agent approved itself (with its reason).

Give ChatThread approvalChoices to offer an approve button per choice, once ("once") or for the whole chat ("chat"), and approvalProof for tools with confirmation: "passkey". It gets the tool part and the proof method. Such a tool gets a single approve button, and its approval waits for the proof; when the proof throws, the card shows the error and stays open. Without approvalProof it cannot be approved.

<ChatThread
  status={chat.status}
  answerApproval={chat.answerApproval}
  approvalChoices={[
    { value: "once", label: "Only now" },
    { value: "chat", label: "For this chat" },
  ]}
  approvalProof={async (part, method) => {
    const optionsJSON = await getPasskeyChallenge(part);
    return startAuthentication({ optionsJSON });
  }}
>

Every answer is an AiApprovalAnswer: the approval id, approved, the optional reason, and the choice and proof. useAssistantChat sends them to the server as approvals.

Chat applies them to the stored message, checks passkey proofs with the tool base's verifyProof, stores choice: "chat" in the chat's approvedTools, and streams again: the agent runs the approved tools and continues the same message, which is saved under the same id. Approvals of tools with a proof always hold for one call, whatever the choice.

Tool cards

Every tool part renders as a ToolCallCard with the tool's title (from tool()) and an icon for its kind: a search icon for reads, a pencil for writes, a trash can for deletes. Most tools need nothing on the client.

Give a tool its own card with a ToolRenderer, and pass the renderers to ChatThread as toolRenderers:

<ChatThread status={chat.status} toolRenderers={[webSearchRenderer]}>

Tools without a Tulip title need one, such as a provider's web search. See Tool renderers.

On this page